动态加载布局分为导入xml控件和新建控件两种,添加至原布局中,适用于动态变化的界面和不适合用xml固定布局的情况
1、自己新建xml布局并与原来的activity所显示的布局相关联
//初始化LayoutInflater MyActivity即当前所在Activity
LayoutInflater mInflater=LayoutInflater.from(MyActivity.this);
//新建view 并从xml布局文件中初始化布局(自定义效果的布局文件)
View view=mInflater.inflate(R.layout.myview);
//初始化textView(需要的布局控件)
TextView textView=(TextView)view.findViewById(R.id.text);
textView.setText("自定义");
//布局中初始化linearLayout控件
LinearLayout layout=(LinearLayout)findViewById(R.id.linearlayout);
//添加到布局
layout.setOrientation(LinearLayout.HORIZONTAL);layout.addView(view);
2、新建view控件添加到原来的布局中
//布局中初始化linearLayout控件
LinearLayout layout=(LinearLayout)findViewById(R.id.linearlayout);
//设置线性布局为横向还是纵向
layout.setOrientation(LinearLayout.HORIZONTAL);
//新建ImageView控件
ImageView img=new ImageView(MyActivity.this);
//创建参数对象,with,height为控件的宽高,参数为整型
LayoutParams mParams= new LayoutParams(width ,height);
//利用参数对象设置控件的参数
img.setLayoutParams(mParams);
//将新建的ImageView对象添加到已有控件中
layout.addView(img);
3.动态添加空间数据给linearlayout
public class Example extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout myLayout = (LinearLayout) findViewById(R.id.my_layout);
LayoutParams lp = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView[] pairs=new TextView[4];
for(int l=0; l<4; l++)
{
pairs[l] = new TextView(this);
pairs[l].setTextSize(15);
pairs[l].setLayoutParams(lp);
pairs[l].setId(l);
pairs[l].setText((l + 1) + ": something");
myLayout.addView(pairs[l]);
}
}
}