2016-09-14 44 views
0

我在RadioGroup中有一个动态创建的单选按钮,因为这些值来自数据库。我希望能够实现setOnClickListener,这样我就可以得到所选的值。每当我尝试点击单选按钮时,什么也不显示。如何实现setOnClickListener从动态创建的RadioButton中获取选定的值Android

public void viewAll() { 

    Cursor res = myDb.getAllData(); 

    LinearLayout bg = (LinearLayout) findViewById(R.id.backgroundSM); 
    LinearLayout display = (LinearLayout) findViewById(R.id.viewAllMsg); 

    final RadioButton[] rb = new RadioButton[5]; 
    rg = new RadioGroup(this); //create the RadioGroup 
    rg.setOrientation(RadioGroup.VERTICAL);//or RadioGroup.VERTICAL 
    res.moveToFirst(); 

    for(int i=0; i<res.getCount(); i++){ 
     rb[i] = new RadioButton(this); 
     //Toast.makeText(getApplicationContext(),res.getString(1) + " ", Toast.LENGTH_LONG).show(); 
     rb[i].setText(" " + res.getString(1) 
       + " " + res.getInt(0)); 
     rb[i].setId(i + 100); 
     rg.addView(rb[i]); 
     res.moveToNext(); 
    } 

    display.addView(rg); // add the whole RadioGroup to the layout 

    rg.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      for(int i = 0; i < 5; i++) { 
       rg.removeView(rb[i]); // now the RadioButtons are in the RadioGroup 
      } 

      int id = rg.getCheckedRadioButtonId(); 
      Toast.makeText(getApplicationContext(),id + " worked", Toast.LENGTH_LONG).show(); 

     } 
    }); 


} 

enter image description here

什么是错我的代码?非常感谢你的帮助。

+0

你可能想独立点击听众,而不是一个监听器设置为单选按钮到整个组视图。 http://stackoverflow.com/questions/13529361/how-to-attach-a-listener-to-a-radio-button/ –

+1

为了清楚起见,“View.OnClickListener”适用于整个视图。你想要一个'OnCheckedChangeListener' –

回答

1

选定的位置将被保存在position可变

rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(RadioGroup radioGroup, int id) { 
      for (int i = 0; i < radioGroup.getChildCount(); i++) { 
       if (radioGroup.getChildAt(i).getId() == id) { 
        position = i + 1; //+1 is used to have a start value of 1 like your example 
        break; 
       } 
      } 
     } 
    }); 
+0

嗨,对不起,回复晚!非常感谢你,我现在可以获得价值。 –

+0

欢迎您! –

相关问题