如何在代码中动态添加布局以及相关的控件

    最近碰到这么个需求:要在代码中动态添加布局,这个布局的个数是由后台给出的数据决定的,而且要结合xml中布局文件,一起构成总布局。不知道你们听懂没,反正就是这样的,要在代码中根据数据的个数生成布局文件添加插入在xml已有布局的顶端。

  上面就是需求。然后自己写了个Demo,解决了这个问题。

假定xml布局文件如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ll_layout" >

    <TextView 
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="哈哈"
        />
</RelativeLayout>

这里给出的是一个相对布局,相对布局上边只有一个TextView控件,显示文字"哈哈",然后自己需要在代码中在该控件上边动态添加布局文件.自己首先试了下,一直添加不了在顶端,只能在该控件边。

想了个法子,修改该布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/ll_layout" >


    <LinearLayout 
        android:id="@+id/ll_tdw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        /> 
    <TextView 
        android:id="@+id/tv"
        android:layout_below="@+id/ll_tdw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="哈哈"
        />
</RelativeLayout>

添加一个空的线性布局文件,设置方向为垂直向下,然后设置TextView控件显示在他下面,接下来我们只需要往ll_tdw的线性布局文件添加任何东西即可。

package com.example.linealayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

	private LinearLayout ll_tdw;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		ll_tdw = (LinearLayout) findViewById(R.id.ll_tdw);
		for(int i=0;i<3;i++){
			LinearLayout ll = new LinearLayout(MainActivity.this);
			TextView text = new TextView(MainActivity.this);
			text.setText("桃花"+i);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
			
			ll.setLayoutParams(params);
			ll.addView(text);
			ll_tdw.setOrientation(LinearLayout.VERTICAL);
			ll_tdw.addView(ll);
		}
	}
}

这样就实现了效果。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值