1. 程式人生 > >android中動態新增元件

android中動態新增元件

</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就不會出錯。具體原因請大家指正。