加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果ViewGroup的宽度在xml中是’match_parent’/’fill_parent’

发布时间:2020-12-16 00:42:16 所属栏目:百科 来源:网络整理
导读:我在activity_main.xml中将LinearLayout定义为根元素. 情况1:从onCreate()我尝试在这个垂直LinearLayout中添加Button,让我困惑的是,根据Google的API,我尝试在按钮上调用setWidth(20)然后在ViewGroup中添加它,但Button占用宽度’match_parent’而不是20dp. L
我在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);

情况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);

情况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);

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

提前致谢.

您需要为按钮视图定义适当的LayoutParams.然后将其添加到firstLayout.
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params.height = XX;
params.width = XX;
button.setLayoutParams(params);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读