簡單:我想用 1個寬度為 0dp的子元素來。
父 xml:
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:
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">
子對象正被添加: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);
如何用 0 dp/體重來膨脹孩子? 當然,就像你看到的,我已經定義了父對象的weight_sum 。