如何实现 setOnClickListener 要从选定的值动态创建 RadioButton Android

标签: Android
发布时间: 2016/10/10 21:16:32
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有内的动态创建的单选按钮 RadioGroup 因为价值观来自数据库。我想要能够执行 setOnClickListener 所以我可以得到任何选定的值。每当我试着点击收音机 button ,未显示任何内容。

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

我的代码有什么错误?太感谢你的帮助。

解决方法 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;
                }
            }
        }
    });
赞助商