我正在尝试从单选按钮组获取单选按钮的文本,但失败了。
这是我得到的错误信息:
05-06 17:32:30.317 20460-20460/pt.smartgeo.aees E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: pt.smartgeo.aees, PID: 20460
java.lang.NullPointerException
at pt.smartgeo.aees.CreatePoint$1.onClick(CreatePoint.java:121)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
这是我的广播组:
<RadioGroup
android:id="@+id/potencia"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/nColuna"
android:layout_toRightOf="@+id/Potencia">
<RadioButton
android:id="@+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="100W" />
<RadioButton
android:id="@+id/rb3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="150W" />
<RadioButton
android:id="@+id/rb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="250W" />
<RadioButton
android:id="@+id/rb4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="400W" />
</RadioGroup>
这就是我试图让它成为我的广播组文本的地方:
RadioGroup group = (RadioGroup) view.findViewById(pt.smartgeo.aees.R.id.potencia);
int selectedId = group.getCheckedRadioButtonId();
RadioButton radioButton = (RadioButton) view.findViewById(selectedId);
Toast.makeText(getActivity().getApplicationContext(),
"rebenta? " + radioButton.getText() , Toast.LENGTH_SHORT).show();
我已经看到我的 selectID 不为空,而且我选择的每个单选按钮都不同。但是我的 toast 有 java 空指针
我做的一些 logcat 和实际结果:
Log.d("id do group", "Id do group: " + group.getId());
Log.d("selected do group", "id do selected radio button " + group.getCheckedRadioButtonId());
Log.d("selectedid", "selected id: " + selectedId);
结果:
05-07 10:26:15.374 13928-13928/pt.smartgeo.aees D/id do group﹕ Id do group: 2131296349
05-07 10:26:15.374 13928-13928/pt.smartgeo.aees D/selected do group﹕ id do selected radio button 2131296353
05-07 10:26:15.374 13928-13928/pt.smartgeo.aees D/selectedid﹕ selected id: 2131296353
最佳答案
单选按钮没有 android:id
属性,它们都没有使用 android:checked = "true"
。不确定你是否用代码检查过你的 radio 。
关于android - Radio Group - 获取选定的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23500264/