</pre><pre name="code" class="html"> public void choices_add(View v){ if(choicesNumber>2){ ImageView choice_ImageView=(ImageView)findViewById(choicesNumber+100); choice_ImageView.setVisibility(View.INVISIBLE); } ++choicesNumber;//添加choices的个数 RelativeLayout new_choice_relativeLayout=getRelativeLayout(); LinearLayout.LayoutParams LP_FW = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); choices_linearLayout.addView(new_choice_relativeLayout, LP_FW); } public RelativeLayout getRelativeLayout(){ RelativeLayout new_choice_relativeLayout=new RelativeLayout(this); new_choice_relativeLayout.setId(choicesNumber); //添加TextView TextView tv = new TextView(this); RelativeLayout.LayoutParams RL_WW = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);//尤其注意这个位置,用的是父容器的布局参数 RL_WW.addRule(RelativeLayout.ALIGN_PARENT_LEFT); tv.setLayoutParams(RL_WW); tv.setPadding(10, 0, 0, 0); tv.setText(choicesNumber+"."); tv.setTextColor(Color.rgb(0xa0, 0x00, 0x00)); tv.setTextSize(20); new_choice_relativeLayout.addView(tv); //添加EditText EditText editText=new EditText(this); RelativeLayout.LayoutParams RL_FW = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); RL_FW.setMargins(30, 0, 30, 0); editText.setLayoutParams(RL_FW); new_choice_relativeLayout.addView(editText); //添加imageView final ImageView imageView=new ImageView(this); imageView.setId(choicesNumber+100); RL_WW = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); RL_WW.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); imageView.setPadding(0, 0, 3, 0); imageView.setLayoutParams(RL_WW); imageView.setImageResource(R.drawable.ic_del); new_choice_relativeLayout.addView(imageView); imageView.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { // TODO Auto-generated method stub System.out.println("点击的imageView的ID号为:"+imageView.getId()); RelativeLayout relativeLayout=(RelativeLayout)findViewById(choicesNumber); //relativeLayout.setVisibility(View.GONE); choices_linearLayout.removeView(relativeLayout); --choicesNumber; System.out.println("点击的imageView后choicesNumber为:"+choicesNumber); if(choicesNumber>2){ ImageView choice_ImageView=(ImageView)findViewById(choicesNumber+100); choice_ImageView.setVisibility(View.VISIBLE); } } }); return new_choice_relativeLayout; }动态添加控件,然后通过ID号删除,但是删除函数如果用View.gone时会出现bug,但是用Remove就不会出错。具体原因请大家指正。
android中动态添加组件
时间:2024-3-2 17:13 作者:韩俊 分类: Android
标签: android