2016-09-14 15 views
0

RadioGroupの中に動的に作成されるラジオボタンがあります。値はデータベースから来ているためです。 setOnClickListenerを実装できるようにしたいので、選択した値が何であれ取得できます。ラジオボタンをクリックしようとすると、何も表示されません。動的に作成されたRadioButtonから選択された値を取得するためにsetOnClickListenerを実装する方法

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

選択した位置は、あなたがグループ全体のビューにラジオボタンではなく、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

あなたは大歓迎です! –

関連する問題