问题:在某个主要Layout里面有个LinearLayout,用来动态加载别的view页面,若是须要加载的动态view内容很空洞(例如没有足够的Text长度来撑起整个layout宽度),这时候这个被加载的view就会不能以fill_parent的width来显示。html
如图: java
实际想要的效果为:
android
java code:
ide
- public class TestActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
- View view = getLayoutInflater().inflate(R.layout.test, null);
- layout.addView(view);
- }
- }
main 布局:布局
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#fff"
- android:orientation="vertical" >
-
- <LinearLayout
- android:id="@+id/layout"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
- </LinearLayout>
-
- </LinearLayout>
test 布局:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:background="#fff"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="测试页面" />
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_margin="5dip"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="帐号:" />
-
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
-
- <LinearLayout
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:layout_margin="5dip"
- android:orientation="horizontal" >
-
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="密码:" />
-
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
-
- </LinearLayout>
解决办法:
在动态view的添加代码前定义一个LayoutParams,而后在添加view时明肯定义一下这个view的LayoutParams测试
- public class TestActivity extends Activity {
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
- View view = getLayoutInflater().inflate(R.layout.test, null);
- LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
- layout.addView(view, params);
- }
- }