【发布时间】:2010-10-28 16:06:47
【问题描述】:
我创建了一个非常简单的活动,在该活动中,我使用 java 代码而不是 xml 创建和设置视图。我传递给外部 LinearLayout 的宽度虽然完全没有效果(200)。无论我在这里传递什么值,视图都会显示在屏幕的整个宽度上。
(请注意,这只是示例代码;我知道在实际应用中您不会使用固定值。我只是想在此处指出我的问题,以便于说明)。 p>
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// outer linear layout
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LinearLayout.LayoutParams(
200, // *** this param has no effect, regardless of the value I set here ***
LinearLayout.LayoutParams.FILL_PARENT
));
ll.setBackgroundColor(Color.parseColor("#00ff00"));
// inner linear layout
LinearLayout ll2 = new LinearLayout(this);
ll2.setLayoutParams(new LinearLayout.LayoutParams(
100, // ** this width for the inner view is working fine **
LinearLayout.LayoutParams.FILL_PARENT
));
ll2.setBackgroundColor(Color.parseColor("#0000ff"));
ll.addView(ll2);
setContentView(ll);
}
}
但如果我替换 setContentView(ll); 并使用 xml 布局而不是外部 LinearLayout 的值为 200px,它会正确应用并且视图只占用屏幕的 200px。
setContentView(com.example.R.layout.main);
main.xml 在哪里:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="200px"
android:layout_height="fill_parent"
android:background="#ff0000"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
为什么在java代码中为外部布局设置固定宽度没有效果?
【问题讨论】: