我试图从一个带有单选项选择列表的片段调用一个对话框窗口,但是当我点击该按钮时,只有屏幕淡出没有任何显示...
通话功能:
private void showDialog() {
myDialog dialog = new myDialog();
dialog.show(getActivity().getSupportFragmentManager(),"dialog");
}
对话类:
public class Dialog extends DialogFragment {
final String[] items= {"item 1","item 2","item 3"};
String selection;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose One").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
selection = items[which];
break;
case 1:
selection = items[which];
break;
case 2:
selection = items[which];
break;
default:
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "item selected: " + selection, Toast.LENGTH_SHORT).show();
}
});
return super.onCreateDialog(savedInstanceState);
}
}
答案 0 :(得分:2)
在onCreateDialog
中,您应该返回您创建的Dialog
:
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Choose One").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
selection = items[which];
break;
case 1:
selection = items[which];
break;
case 2:
selection = items[which];
break;
default:
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "item selected: " + selection, Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
将您的班级Dialog
重命名为CustomDialog
或类似名称,因为它已被使用
你可以展示它:
private void showDialog() {
CustomDialog dialog = new CustomDialog();
dialog.show(getActivity().getSupportFragmentManager(),"dialog");
}
答案 1 :(得分:1)
不要返回super.onCreateDialog(savedInstanceState)
,而是返回builder.create()