问题
I'm trying to remove the OK button completely so that an item is automatically clicked when selected. I noticed that this is Android's preferred way of doing it. I don't need a "cancel" button because I want to prevent null selected.
Dialog Fragment
public class SingleChoiceClass extends
DialogFragment {`
final CharSequence[] items = {"b1", "b2", "b3", "b4"};
String selection;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());`
builder.setTitle("Choose").setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1){
case 0:
selection = (String) items[arg1];
break;
case 1:
selection = (String) items[arg1];
break;
case 2:
selection = (String) items[arg1];
break;
case 3:
selection = (String) items[arg1];
break;
}
}
}).setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Display toast with the user's selection
Toast.makeText(getActivity(), "Your choice is : " + selection, Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
The code works fine as it is, I just want to get selected item without having to click "OK" button. It saves user's time.
回答1:
I'm not sure if this is the Android recommended way of doing this but I finally figured out a way of achieving the exact behavior I want.
public class SingleChoiceClass extends
DialogFragment {
final CharSequence[] items = {"b1", "b2", "b3", "b4"};
String selection;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
final MainActivity activity = (MainActivity) getActivity();
builder.setTitle("Choose")
.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
switch (arg1){
case 0:
selection = (String) items[arg1];
Toast.makeText(getActivity(), "" + selection,Toast.LENGTH_SHORT).show();
// Do your magic
dismiss();
break;
case 1:
selection = (String) items[arg1];
Toast.makeText(getActivity(), "" + selection,Toast.LENGTH_SHORT).show();
// Do your magic
dismiss();
break;
case 2:
selection = (String) items[arg1];
Toast.makeText(getActivity(), "" + selection,Toast.LENGTH_SHORT).show();
// Do your magic
dismiss();
break;
case 3:
selection = (String) items[arg1];
Toast.makeText(getActivity(), "" + selection,Toast.LENGTH_SHORT).show();
// Do your magic
dismiss();
break;
}
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Exit
activity.finish(); //Or find a way to relaunch Dialog
}
});
return builder.create();
}
}
来源:https://stackoverflow.com/questions/33885034/how-to-remove-ok-button-from-dialog-fragment-in-android