gpt4 book ai didi

android - DialogFragment 中的 RadioButton 监听器

转载 作者:太空狗 更新时间:2023-10-29 16:40:12 25 4
gpt4 key购买 nike

我尝试实现 RadioGroup View 并将其放入 DialogFragment 中,但出了点问题。我已按照本教程进行操作

http://developer.android.com/guide/topics/ui/controls/radiobutton.html

而是在 Activity 中, View 在 DialogFragment 中初始化:

public class MenuDialog extends DialogFragment {

public MenuDialog(){}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_layout, container);
this.getDialog().setTitle("title");
return view;
}

public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if(checked) {
Log.i("MENU", ((RadioButton)view).getText());
}
break;
case R.id.radio2:
if(checked) {
Log.i("MENU", ((RadioButton)view).getText());
}
break;
case R.id.radio3:
if(checked) {
Log.i("MENU", ((RadioButton)view).getText());
}
break;
case R.id.radio4:
if(checked) {
Log.i("MENU", ((RadioButton)view).getText());
}
break;
}
this.getDialog().dismiss();
}

xml:

<?xml version="1.0" encoding="utf-8"?>

<RadioGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/radio_group" >

<RadioButton
android:id="@+id/radio1"
android:text="20" />

<RadioButton
android:id="@+id/radio2"
android:text="40" />

<RadioButton
android:id="@+id/radio3"
android:text="60" />

<RadioButton
android:id="@+id/radio4"
android:text="80" />
</RadioGroup>

onRadioButtonClicked 监听器,实现方式同教程。现在,当启动对话框时,如果我点击单选按钮,我会收到此错误:

09-27 09:41:08.018: E/AndroidRuntime(7447): FATAL EXCEPTION: main
09-27 09:41:08.018: E/AndroidRuntime(7447): java.lang.IllegalStateException: Could not
find a method onRadioButtonClicked(View) in the activity class
android.view.ContextThemeWrapper for onClick handler on view class
android.widget.RadioButton with id 'radio1'

怎么了?

最佳答案

我宁愿在 fragment 内部实现点击处理程序并动态添加监听器(通过 java 而不是 XML)。所以我会做这样的事情:

public class MenuDialog extends DialogFragment implements OnClickListener{
[...]
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.menu_layout, container);
view.findViewById(R.id.radio1).setOnClickListener(this);
view.findViewById(R.id.radio2).setOnClickListener(this);
//and so on [...]
this.getDialog().setTitle("title");
return view;
}

@Override
public void onClick(View v){
[...]
}

关于android - DialogFragment 中的 RadioButton 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19045739/

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