我已经实现了按下后退按钮时显示的是/否对话框。如果用户单击“是的,我想离开”,应用程序将关闭。在我的模拟器中一切正常,但是当我在手机上安装应用程序时,点击“是”时,应用程序会后退一步/操作,只有在完成我在其中所做的所有更改时才会关闭。它只发生在我的 Galaxy s4 上,最有趣的是,当我一个月前在同一部手机上安装该应用程序时,我没有遇到同样的问题。无论如何,这是yes no对话的代码:
public class YesNoDialog extends DialogFragment {
Button btnYes, btnNo;
static String dialogTitle;
public interface YesNoDialogListener {
void onFinishYesNoDialog(boolean state);
}
public YesNoDialog(){
}
public void setDialogTitle(String title){
dialogTitle = title;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_yes_no_dialog, container, false);
btnYes = (Button) view.findViewById(R.id.btnYes);
btnNo = (Button) view.findViewById(R.id.btnNo);
getDialog().setTitle(dialogTitle);
btnYes.setOnClickListener(btnListener);
btnNo.setOnClickListener(btnListener);
return view;
}
private View.OnClickListener btnListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
YesNoDialogListener activity = (YesNoDialogListener) getActivity();
String state = ((Button) v).getText().toString();
if (state.equals("Yes")) {
activity.onFinishYesNoDialog(true);
} else {
dismiss();
}
}
};
}
并在MainActivity
:
@Override
public void onFinishYesNoDialog(boolean state) {
if (state){
super.finish();
}
}
private void showYesNoDialog() {
YesNoDialog yesNo = new YesNoDialog();
yesNo.setDialogTitle("Leaving Project Planner");
yesNo.show(mFragmentManager, "yes/no dialog");
}
public void onBackPressed() {
showYesNoDialog();
}