我想提示用户使用on back press退出应用程序,但是我很难在我的片段中实现这个
public class HomeFragment extends Fragment {
public HomeFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home, container, false);
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
HomeFragment.super.onBackPressed();
}
}).create().show();
}
}
答案 0 :(得分:1)
使用此代码显示警告对话框
final android.support.v7.app.AlertDialog.Builder alertDialog = new android.support.v7.app.AlertDialog.Builder(getActivity());
alertDialog.setTitle("Your text");
alertDialog.setMessage("Your custom text")
.setCancelable(true).setPositiveButton("Rate Us", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//your custom toast
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
}).create().show();
}
答案 1 :(得分:1)
你不能在Fragments中做到这一点,但是在你的情况下,因为每个片段都在一些Activity上运行。
将onBackPressed代码放在包含片段的活动上。
答案 2 :(得分:0)
你能尝试这种方式并检查它是否有效:
@Override
public void onDetach() {
super.onDetach();
PUT YOUR CODE HERE
}