0
レイアウトの下部にViewを追加して、この要素の最後にラインセパレータを追加しました。問題は、このビューをレイアウトに入れた後に画面の幅全体が塗りつぶされますが、Viewを取り出すと正しいサイズ(テストで約400dp)が表示されることです。追加されたビューがレイアウトを画面全体に塗りつぶすのはなぜですか?レイアウトにビューを追加すると、レイアウト全体の幅が変更されるのはなぜですか?
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:orientation="vertical"
android:paddingLeft="6dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/text_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:textColor="@android:color/darker_gray"
android:textSize="12sp"
tools:text="Hello, Label"
android:paddingBottom="6dp"
android:paddingLeft="6dp"/>
<TextView
android:id="@+id/text_error"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:textColor="@color/sr_red"
android:textSize="12sp"
tools:text="Error!"/>
</LinearLayout>
<!-- this View causes the parent layout to fill the whole screen width-->
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:layout_marginTop="2dp"
android:background="@android:color/darker_gray"
/>
</LinearLayout>
問題を引き起こしているのは一番下にあります。
私はこのようビューを変更しています:ここ
val inputLayout = createLabelLayout(context, component.name, button)
viewGroup.addView(inputLayout.root)
inputLayout.setWidth(width)
し、関連するクラスが
private fun <T : View> createLabelLayout(context: Context, text: String, child: T): LabelLayout<T> {
val layout = LabelLayout(context, child)
layout.label.text = text
return layout
}
private class LabelLayout<out T : View>(context: Context, child: T) {
val root = LayoutInflater.from(context).inflate(R.layout.item_custom_field_label, null, false) as ViewGroup
val label = root.findViewById(R.id.text_label) as TextView
val error = root.findViewById(R.id.text_error) as TextView
init {
root.addView(child, root.childCount - 1)
}
fun setWidth(width: Int) {
val params = root.layoutParams
params.width = width
root.layoutParams = params
}
}
あなたのルート 'LinearLayout'の' width'と 'height'は' match_parent'に設定されています。少なくとも、 'height'は' wrap_content'でなければなりません。 –
しかし、setWidth()を呼び出すと、ルート要素の幅がリセットされます。 そして、xmlの最下部のビュー(分割線であるビュー)をコメントアウトしてから、ルート要素が正しい幅にフォーマットされます。だから、それは問題を引き起こしているレイアウトの最後のビューであるようです。 –