android 动态修改 layout

再次把这个功能记下来,方便自己以后查询


这是个动态修改layout布局



LayoutInflater inflater = getLayoutInflater();
LinearLayout test = (LinearLayout)inflater.inflate(R.layout.main3, null);

FrameLayout layout2 = (FrameLayout)findViewById(R.id.myframe);
layout2.setBackgroundColor(Color.RED);
RelativeLayout sublayout = (RelativeLayout)findViewById(R.id.testrelin);
layout2.removeView(sublayout);
layout2.addView(test);

 

我的XML布局如下:


android:id="@+id/widget61"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
android:id="@+id/testbt3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/testbt1" />
android:id="@+id/testbt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/testbt4" />
android:id="@+id/testbt4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_toRightOf="@+id/testbt2" />
android:id="@+id/myframe"
android:layout_width="320dp"
android:layout_height="385dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true">
android:id="@+id/testrelin"
android:layout_width="320dp"
android:layout_height="384dp">
android:id="@+id/widget68"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />


android:id="@+id/testbt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />




另外更改View显示

LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View myview = (View)inflater.inflate(R.layout.myrelative, null,true);
//View myview = (View)inflater.inflate(R.layout.main3, null,true);
setContentView(myview);


你可能感兴趣的:(android学习)