一.实例化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);