简单:我想给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>


然后通过以下方式添加孩子:

Parent.addView(new KeyButton(context) );




问题是android:layout_weight似乎不采取任何措施,并且子级的layout_width保持为“ 0dp”。如果将宽度更改为50dp,我可以看到正确膨胀的孩子。

还尝试在添加时以编程方式添加参数:

KeyButton bt = new KeyButton(context);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
bt.setLayoutParams(lp);
Parent.addView(bt);


如何为孩子充气0dp /体重?当然,如您所见,我已经定义了父级的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);

10-08 19:32