最近项目中需要动态的添加布局,查了网上的一些方法,自己总结了一下,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