我在activity_main.xml文件中定义了一个LinearLayout作为根元素。
情况1:在onCreate()方法中,我试图向这个垂直LinearLayout中添加Button,但是让我困惑的是,根据Google的API,我尝试在将Button添加到ViewGroup之前调用setWidth(20)方法,但Button占据了“match_parent”的宽度,而不是20dp。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical"
android:id="@+id/first_layout">
</LinearLayout>
//Inside onCreate() of activity..
LinearLayout firstLayout = (LinearLayout) findViewById(R.id.first_layout);
Button button = new Button(this);
button.setText(R.string.click_on_me);
button.setWidth(20);
firstLayout.addView(button);
案例2:当将LinearLayout的layout_width设置为“wrap_content”,并调用setWidth(20)时,它现在被认为是给定的明确宽度值,即20dp。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical"
android:id="@+id/first_layout">
</LinearLayout>
//Inside onCreate() method
LinearLayout firstLayout = (LinearLayout) findViewById(R.id.first_layout);
Button button = new Button(this);
button.setText(R.string.click_on_me);
button.setWidth(20);//In this case, its working
firstLayout.addView(button);
情况三:最终,移除了我自定义的setWidth(20)方法调用后,按钮获取了'wrap_content'宽度。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_margin="10dp"
android:orientation="vertical"
android:id="@+id/first_layout">
</LinearLayout>
//Inside onCreate() method.
LinearLayout firstLayout = (LinearLayout) findViewById(R.id.first_layout);
Button button = new Button(this);
button.setText(R.string.click_on_me);
firstLayout.addView(button);
问题:通过第2个案例可以明确,如果我想显式使用setWidth()方法,则不需要使用LayoutParams。那么在第4个案例中:将LinearLayout的宽度设置为“match_parent”,同时调用button.setWidth(20)。 但是为什么Button仍然不采用明确给定的宽度值,输出与CASE 1完全相同。
提前感谢。