我在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 举报,一经查实,本站将立刻删除。