-3

我将单选按钮添加到我的单选组中,我想为按钮添加一个属性,以便在单击添加的按钮之一时调用一个方法。我该怎么做,我尝试搜索,但没有找到答案。我有一个 for 循环来添加单选按钮

enter code here

RadioGroup group = (RadioGroup) findViewById(R.id.RadioGroup);
RadioButton button;
String accounts= msg.getData().getString("text");
String[] SepAccounts= accounts.split(":");
    for (int i=0; i<SepAccounts.length;i++)
        SepAccounts[i]= SepAccounts[i].replaceAll("-"," ");
    Context context= group.getContext(); 

    for (int i=0; i < SepAccounts.length; i++){ 
            button = new RadioButton(context);
            button.setText(SepAccounts[i]);
        group.addView(button);
    }

这是我添加单选按钮的代码的一部分

这就是我创建广播组的地方

<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_below="@id/NFCHeaderTextView"
android:layout_width="fill_parent"
android:background="@drawable/back"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/RadioGroup"
    android:onClick="onRadioButtonClicked">

</RadioGroup>
4

2 回答 2

1

你试过这个吗?

radioButton.setOnClickListener(listener);

您的侦听器将需要实现 OnClickListener。

于 2013-01-24T16:53:31.467 回答
1

将 OnClickListener 添加到每个按钮,然后再将其添加到组中...

    RadioGroup group = (RadioGroup) findViewById(R.id.RadioGroup);
    RadioButton button;
    String accounts = msg.getData().getString("text");
    String[] SepAccounts = accounts.split(":");
    for (int i = 0; i < SepAccounts.length; i++)
        SepAccounts[i] = SepAccounts[i].replaceAll("-", " ");
    Context context = group.getContext();

    for (int i = 0; i < SepAccounts.length; i++) {
        button = new RadioButton(context);
        button.setText(SepAccounts[i]);
        button.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doStuff(v);
            }
        });
        group.addView(button);
    }

...

private void doStuff(View v)
{
    // radio button "v" was clicked
}

查看文档以获取有关 OnClickListener http://developer.android.com/reference/android/view/View.OnClickListener.html的更多信息

于 2013-01-24T16:53:48.873 回答