2014年1月21日 星期二

Android 開發 (十七) 如何動態加入view

在作專案時,總是有必須動態增加view的情形
在這邊示範一個簡單的範例


  for(int i=0; i<10;i++){

   RadioButton btn  = new RadioButton(this);
   LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
   btn.setLayoutParams(params);
   rootLayout.addView(btn);
  }

這是簡單的方式將RadioButton 加入 rootLayout裡  其中  rootLayout為RadioGroup

下圖為結果

上面是較為簡單的範例  假設今天我們必須customize我們的layout
就必須取得inflater取得inflater的方式有兩種

LayoutInflater inflater = LayoutInflater.from(this);
LayoutInflater LayoutInflater =  
             (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

在取得 inflater之後就可以使用 findviewbyId去取得單一的view
下面有簡單的範例供參考

  for(int i=0; i<10;i++){
   LayoutInflater LayoutInflater =  
             (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   View view = LayoutInflater.inflate(R.layout.custom_layout, null);
   TextView txt = (TextView)view.findViewById(R.id.txtview);
   txt.setText(String.valueOf(i));
   rootLayout.addView(view);
  }

上面的sample code在取得 inflater之後,使用 findviewbyId取得textView,並且設定了text
這樣就完成了客製化


最後附上 sample code

沒有留言:

張貼留言