最近碰到这么个需求:要在代码中动态添加布局,这个布局的个数是由后台给出的数据决定的,而且要结合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);
}
}
}
这样就实现了效果。