android 动态添加View 两种方法

一.实例化View

RelativeLayout relativeLayout = new RelativeLayout(view.getContext());
RelativeLayout.LayoutParams relLayoutParams=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
id_layout_drug.addView(relativeLayout, relLayoutParams);
TextView textView = new TextView(view.getContext());
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//与父组件顶部对齐
lp1.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
lp1.setMargins(10,5,10,5);
textView.setTextSize(16);
textView.setText("乌克丽丽");
relativeLayout.addView(textView,lp1);

二.inflate 复杂的带参数的我们就是用inflate来从xml实例化 记得去除parent!

   RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                //与父组件顶部对齐
                lp2.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
                lp2.setMargins(10,5,10,5);
//                com.zcw.togglebutton.ToggleButton button = new  com.zcw.togglebutton.ToggleButton(view.getContext());
                LinearLayout temp= (LinearLayout)getLayoutInflater().inflate(R.layout.toggle_layout, null);
                ToggleButton button=(ToggleButton) temp.findViewById(R.id.id_togglebutton);
                //如果不解除button的父子关系会报错 The specified child already has a parent. You must call removeView
                ((ViewGroup)button.getParent()).removeView(button);
                relativeLayout.addView(button,lp2);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值