Android 代码动态加载布局

动态加载布局分为导入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]);
        }
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值