我的主活动有一个按钮,它显示一个带有3个选项的对话框来自字符串数组。 对话/弹出工作,但我如何在主要活动中选择用户?
主要活动的功能(是的,需要一个int或者返回):
public void showDialog(View view)
{
DifDialog dia = new DifDialog();
dia.show(getFragmentManager(), "test");
}
类DifDialog:
public class DifDialog extends DialogFragment {
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.difficulty);
builder.setItems(R.array.diff, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
Dialog dialog=builder.create();
return dialog; }}
我在主要活动中需要来自onClick的“which”..(我认为;)
答案 0 :(得分:1)
如果您的目标是让对话框告诉活动单击了哪个按钮,那么您可以使用界面作为从对话框到活动的回调。
要执行此操作,您应首先在对话框片段中定义界面。
在显示对话框片段的活动中,有一个名为onAttachFragment()的acivity生命周期方法被调用。调用此方法时,请检查要添加的片段是否为对话框片段。如果是,则在此处设置侦听器。
现在,当您在对话框片段中单击按钮时,您可以使用侦听器对活动进行回调。
在对话框片段代码中:
public class DifDialog extends DialogFragment {
private DifDialogListener mListener;
public interface DifDialogListener {
void onButtonOneClicked();
void onButtonTwoClicked();
void onButtonThreeClicked();
}
public void setListener(DifDialogListener listener) {
if (listener == null) {
throw new NullPointerException();
}
mListener = listener;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.difficulty);
builder.setItems(R.array.diff, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mListener.onButtonOneClicked();
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
mListener.onButtonTwoClicked();
} else if (which == DialogInterface.BUTTON_NEUTRAL) {
mListener.onButtonThreeClicked();
}
});
Dialog dialog=builder.create();
返回对话框; }}
在您的活动中:
showDialog() {
DifDialog dia = new DifDialog();
dia.show(getFragmentManager(), "test");
}
@Override
onAttach(Fragment fragment) {
if (fragment instanceOf DifDialog) {
DifDialog frag = (DifDialog) fragment;
frag.setListener(new DifDialogListener() {
@Override
onButtonOneClicked() {
//Button one was clicked
}
@Override
onButtonTwoClicked() {
//Button two was clicked
}
@Override
onButtonThreeClicked() {
//Button three was clicked
}
});
}
}
答案 1 :(得分:0)
希望这有帮助
List<String> optionsList = new ArrayList<String>();
optionsList.add("Option One");
optionsList.add("Option Two");
optionsList.add("Option Three");
final CharSequence[] options = optionsList.toArray(new CharSequence[optionsList.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Option One")) {
//do something
} else if (options[item].equals("Option Two")) {
//do something
} else if (options[item].equals("Option Three")) {
//do something
}
}
});
builder.show();
}