最近項目中需要動態的添加布局,查了網上的一些方法,自己總結了一下,android中動態加載佈局主要是找準父佈局,注意父佈局的樣式,是linearlayout或者是其他。
代碼如下:
父佈局,其中定義了兩個layout,一個是linearlayout,另一個是RelativeLayout,目的是更清楚的瞭解父佈局不同(實際只用一個),在實現動態加載佈局是所用的包不同(後面會更清楚)
<?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:orientation="vertical"
android:id="@+id/layout_main"
android:background="@android:color/black">
<Button
android:id="@+id/btn_add_view"
android:text="add"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<RelativeLayout
android:id="@+id/rl_addview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"></RelativeLayout>
</LinearLayout>
子佈局,也就是要動態加載的佈局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="#dfdfdf"
android:id="@+id/ddd">
<TextView
android:id="@+id/tv_tv"
android:text="ssssss0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
實現方法:
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.layout_main);
View view = LayoutInflater.from(this).inflate(R.layout.relativeitem, null);
RelativeLayout addViewLayout = (RelativeLayout) view.findViewById(R.id.ddd);
addViewLayout.setId(100);
addViewLayout.setOnClickListener(this);
TextView tView = (TextView) view.findViewById(R.id.tv_tv);
tView.setText("sssss"+i);
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(120, 50);
lp1.topMargin = 40;
lp1.leftMargin=30;
mainLayout.addView(addViewLayout,lp1);
第一行是實例化父佈局,第二行實例化要顯示的view,目的是爲了找到要加載的子佈局以及要是爲子佈局中的控件添加數據,第三行是實例化子佈局,第四行是設置id,第5行設置監聽。
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(120, 50); 這行中的LayoutParams要根據父佈局不同,導入不同的包,也就是第一行的父佈局類型,如果第一行中是 RelativeLayout 就要調用
RelativeLayout.LayoutParams