简单:我想用 1 个宽度为 0dp 的子项来膨胀父项。
父级 xml:
<com.example.KeyPad // extend LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="4" // for the children
android:layout_weight="1" // this is for its parent
android:clickable="true"
android:background="@color/MidnightBlue" >
子类:
public class KeyButton extends RelativeLayout implements View.OnClickListener{
public KeyButton(Context c ) {
super(c);
RelativeLayout v = (RelativeLayout) LayoutInflater.from(c).inflate(R.layout.key_button, this, true);
}
}
}
它使用 R.layout.key_button xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_weight="1"
android:layout_width="0dp"
android:background="@android:color/holo_red_dark"
android:layout_height="wrap_content">
<TextView ... />
</RelativeLayout>
child 正在通过以下方式添加:
Parent.addView(new KeyButton(context) );
问题是 android:layout_weight
没有采取行动,子项的 layout_width 保持在“0dp”。如果我将宽度更改为 50dp,我可以看到正确充气的 child 。
还尝试在添加时以编程方式添加参数:
KeyButton bt = new KeyButton(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
bt.setLayoutParams(lp);
Parent.addView(bt);
如何给 child 充气 0dp/weight?当然,如您所见,我已经定义了父项的 weight_sum。
最佳答案
您使用了 LinearLayout.LayoutParams
,但按钮的父级是 RelativeLayout
。
试试这个:
KeyButton bt = new KeyButton(context);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(0, RelativeLayout.LayoutParams.WRAP_CONTENT,1.0f);
Parent.addView(bt, lp);
关于android - 使用 0dp 布局宽度和重量给 child 充气(以编程方式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24784635/