小编its*_*oel的帖子

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

我在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)

android android-layout

5
推荐指数
1
解决办法
1522
查看次数

标签 统计

android ×1

android-layout ×1