【发布时间】:2021-10-24 18:41:50
【问题描述】:
我在重置 align_parent 时遇到问题。这个想法是我们在窗口中有一个对象,我们可以用按钮控制它,但我有一个问题,如果我按下 setTop,它将到达指示的位置,但是当我按下 setBottom 时,按钮是到位。我的印象是变量重置无法正常工作,但我不明白为什么。也许您知道他是否输入了错误的 removeRule,或者有没有其他方法可以将 align_parent 和 center_horizontal 值设置为 false?
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_margins_train)
val testbox = findViewById<TextView>(R.id.testbox)
val setTop = findViewById<TextView>(R.id.setTop)
val setBottom = findViewById<TextView>(R.id.setBottom)
val parameters = RelativeLayout.LayoutParams(heightBox.toInt(),widthBox.toInt())
val reset = RelativeLayout.LayoutParams(heightBox.toInt(),widthBox.toInt())
.apply { removeRule(RelativeLayout.ALIGN_PARENT_END) }.apply { removeRule(RelativeLayout.ALIGN_PARENT_TOP) }
.apply { removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM) }.apply { removeRule(RelativeLayout.ALIGN_PARENT_START) }
.apply { removeRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { removeRule(RelativeLayout.CENTER_VERTICAL) }
setTop.setOnClickListener {
testbox.layoutParams = reset
testbox.layoutParams = parameters.apply { addRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { addRule(RelativeLayout.ALIGN_PARENT_TOP) }
}
setBottom.setOnClickListener {
testbox.layoutParams = reset
testbox.layoutParams = parameters.apply { addRule(RelativeLayout.CENTER_HORIZONTAL) }.apply { addRule(RelativeLayout.ALIGN_PARENT_BOTTOM) } }
}
XML 代码
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MarginsTrain">
<TextView
android:id="@+id/setTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/testing"
android:layout_centerHorizontal="true"
android:layout_marginBottom="1dp"
android:background="@drawable/customborder_box"
android:paddingHorizontal="2dp"
android:paddingBottom="3dp"
android:textSize="14sp"/>
<TextView
android:id="@+id/setBottom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/testing"
android:layout_centerHorizontal="true"
android:layout_marginTop="1dp"
android:background="@drawable/customborder_box"
android:paddingHorizontal="2dp"
android:paddingTop="3dp"
android:textSize="14sp"/>
<RelativeLayout
android:id="@+id/testing"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@color/teal_200">
<TextView
android:id="@+id/testbox"
android:layout_width="@dimen/testboxWidth"
android:layout_height="@dimen/testboxHeight"
android:background="@color/purple_500"
android:gravity="center"
android:text="@string/RelativeLayoutTestTextBox"
android:textColor="@color/white" />
</RelativeLayout>
</RelativeLayout>
【问题讨论】:
-
您能分享一下您的
activity_margins_train布局吗?
标签: android android-studio kotlin android-layout