android动态加载(添加)布局

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



  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值