2012-10-29 45 views
1

動態創建我有一個疑問......在我的Android應用程序,我有它的GUI是從某些數據動態創建我的SQLite數據庫內的活動......我沒有過任何形式在這個活動中,有一堆TextView的和RadioGroup的和RadioButton的創建一個for循環內,並且由於該循環內部的條件,RadioButton的數量會有所不同。 ..這樣的:方法UI元素在Android

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

      TextView pregunta = new TextView(this); 
      pregunta.setText(c.getString(c.getColumnIndex("texto"))); 
      pregunta.setGravity(Gravity.LEFT); 
      pregunta.setTextColor(Color.rgb(0, 0, 0)); 
      pregunta.setTextSize(15); 
      pregunta.setLayoutParams(params); 
      ll.addView(pregunta); 

      if(c.getString(c.getColumnIndex("tipopregunta")).equals("Si o No")){ 

       RadioGroup rg = new RadioGroup(this); 
       ll.addView(rg); 

       RadioButton b1 = new RadioButton(this); 
       b1.setText("SI"); 
       rg.addView(b1); 

       RadioButton b2 = new RadioButton(this); 
       b2.setText("NO"); 
       rg.addView(b2); 

      }else{ 

       if(c.getString(c.getColumnIndex("tipopregunta")).equals("Seleccion Simple")){ 

        RadioGroup rg = new RadioGroup(this); 
        ll.addView(rg); 

        RadioButton b1 = new RadioButton(this); 
        b1.setText("SI"); 
        rg.addView(b1); 

        RadioButton b2 = new RadioButton(this); 
        b2.setText("NO"); 
        rg.addView(b2); 

        RadioButton b3 = new RadioButton(this); 
        b3.setText("N/A"); 
        rg.addView(b3); 

       } 
      } 
      c.moveToNext(); 
     } 

所以我的問題是如何獲取單選按鈕的用戶所選擇的價值......我的意思是,我有爲每個RadioButton調用方法setOnClickListener()?或者我必須爲每個RadioGroup做?我在哪裏聲明這些語句:在for循環或外部?或者有另一種方式?

我非常非常失去了這裏!任何形式的幫助都會被推崇!謝謝!

回答

0

只有一種方法可以通過使用OnCheckedChangeListener 您可以創建每個監聽器並將其分配給您的RadioGroup,但我不建議這樣做。您可以在資源創建多個ID和循環之前創建只是一個單一的監聽器,並在循環分配給您RadioGroup中(你需要radioGroup中設置,在資源創建ID)。下面是例子:

OnCheckedChangeListener listener = new OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      switch (group.getId()) { 
      case R.id.myradio_group1: 
       // DO your work here 
       break; 

      default: 
       break; 
      } 
     } 
    }; 

    // your loop is here 
    for(int i=0;i<numFilasFormulario;i++){ 
     .... 
     RadioGroup rg = new RadioGroup(this); 
     rg.setId(R.id.myradio_group1); // or simply just using rg.setId(i+1000); 
     // make sure 1000, 1001, 1002, ... is already create at Resource 
     .... 
    } 
+0

嘿!感謝您的回覆!但我不明白你的意思是「確保1000,1001,1002,...已經創建了一個資源」...我是否必須手動修改R類? –

+0

如何在聽者內部訪問單選按鈕?謝謝! –

+0

抱歉遲到回覆,您無需修改​​R類文件。 Android是允許通過添加以下行「<項名稱=」 khd_dashboard_layout_id「格式=‘整數’類型=‘ID’> 1001」在資源文件預留ID在資源文件 – vsatkh