gpt4 book ai didi

android - 如何在自定义对话框中添加 radiogroup onchecked 监听器

转载 作者:太空宇宙 更新时间:2023-11-03 12:46:16 25 4
gpt4 key购买 nike

我有一个包含单选按钮的自定义对话框,但是当我添加一个 oncheckedchangelistener 时,我的应用程序崩溃了。可能是什么问题?

提前致谢! :D

这是我的代码:

GridViewAdapter adapter = new GridViewAdapter(alcoholType.this, images,names);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {

final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.alcoholdialog);
dialog.setTitle("ORDER " + names.get(position));

radioQuantity = (RadioGroup) findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) findViewById(R.id.quantity1);
quantity2 = (RadioButton) findViewById(R.id.quantity2);

radioQuantity.clearCheck();

radioQuantity.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {


}

});

dialog.show();
}
});

这是错误轨迹:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gin.ordering, PID: 22005
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.RadioGroup.clearCheck()' on a null object reference
at com.example.gin.ordering.alcoholType$1.onItemClick(alcoholType.java:90)
at android.widget.AdapterView.performItemClick(AdapterView.java:339)
at android.widget.AbsListView.performItemClick(AbsListView.java:1549)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3723)
at android.widget.AbsListView$3.run(AbsListView.java:5707)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6918)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)

最佳答案

您需要使用Dialog 的 引用来获取 View 的:

使用:

radioQuantity = (RadioGroup) dialog.findViewById(R.id.radioQuantity);
quantity1 = (RadioButton) dialog.findViewById(R.id.quantity1);
quantity2 = (RadioButton) dialog.findViewById(R.id.quantity2);

你得到 NullPointerException 因为你的 RadioGroup 没有附加到 View 。

同样对于 CheckedListener 使用:

radioQuantity.setOnCheckedChangeListener(new 
RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {

if (checkedId == R.id.quantity1) {
//Your code
} else if (checkedId == R.id.quantity2) {
//Your code
}

}
});

关于android - 如何在自定义对话框中添加 radiogroup onchecked 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43745060/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com