如果ViewGroup的宽度在xml中是'match_parent'/'fill_parent',那么Button的set-setWidth()不起作用?

its*_*oel 5 android android-layout

我在activity_main.xml中将LinearLayout定义为根元素.

情况1:从onCreate()我尝试在这个垂直LinearLayout中添加Button,让我困惑的是,根据Google的API,我尝试在按钮上调用setWidth(20)然后在ViewGroup中添加它,但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);
Run Code Online (Sandbox Code Playgroud)

情况1

情况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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

情况3:最后,删除我对setWidth(20)的自定义调用,Button获取宽度为'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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

问:所以在案例2中很清楚,如果我希望明确使用setWidth()方法,则不需要使用LayoutParams.然后在案例4中:即LinearLayout的宽度设置为'match_parent'而button.setWidth(20)是也被称为.但是为什么Button仍没有明确给定宽度值,再次输出与CASE 1完全相同.

提前致谢.

Ale*_*lan 3

您需要定义一个适合LayoutParams您的按钮视图。然后将其添加到您的firstLayout.

LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.height = XX;
params.width = XX;
button.setLayoutParams(params);
Run Code Online (Sandbox Code Playgroud)