如果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);

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇