如何在RadioButton中设置监听器 - Android

时间:2014-10-28 12:25:12

标签: android button

我在3个不同的LinearLayout中有3个RadioButton。所以,我不能拥有一个RadioGroup。

我如何设置听众? 我尝试使用onCheckedListener:

RadioButton badChoise= (RadioButton) findViewById(R.id.badChoise);
badChoise.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    // TODO Auto-generated method stub

                // i don't know what i need to set for buttonView, and isChecked



                }

如果我在我的RadioButton上设置onClickListener,我有这个错误:

10-28 13:06:10.893: E/AndroidRuntime(29179): FATAL EXCEPTION: main
10-28 13:06:10.893: E/AndroidRuntime(29179): java.lang.NullPointerException
10-28 13:06:10.893: E/AndroidRuntime(29179):    at          
com.example.survey.Survey$1.onClick(Survey.java:73)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at android.view.View.performClick(View.java:4377)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at    android.view.View$PerformClick.run(View.java:18044)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at android.os.Handler.handleCallback(Handler.java:725)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at android.os.Looper.loop(Looper.java:137)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at   android.app.ActivityThread.main(ActivityThread.java:5306)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at java.lang.reflect.Method.invokeNative(Native Method)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at java.lang.reflect.Method.invoke(Method.java:511)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at   com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
10-28 13:06:10.893: E/AndroidRuntime(29179):    at dalvik.system.NativeStart.main(Native Method)

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

我在单选按钮上使用自定义侦听器,因为我的布局与RadioGroup不兼容

首先创建一个监听器

OnClickListener listenerYear = new OnClickListener() {
        @Override
        public void onClick(View v) {

            month = v.getTag().toString(); //Add tags to your view to identify them
        }
    };

然后逐个将您的按钮添加到监听器

RadioButton bt_JAN = (RadioButton) findViewById(R.id.bt_JAN);
bt_JAN.setOnClickListener(listenerMonth);

RadioButton bt_FEB = (RadioButton) findViewById(R.id.bt_FEB);
bt_FEB.setOnClickListener(listenerMonth);

或使用循环添加

for(int i=1;i<=12 ;i++){                
            int resID = getResources().getIdentifier("radio"+i, "id", getPackageName());                
            RadioButton bt = (RadioButton) findViewById(resID);
            bt.setOnClickListener(listenerMonth);
}

答案 1 :(得分:0)

使用RadioGroup并使用getCheckedRadioButtonId()函数。