繁体   English   中英

如何防止后退按钮从主要活动中关闭应用程序?

[英]How do you prevent the back button from closing an application from the main activity?

尝试显示片段时,我的活动关闭遇到问题。 我试图让我的应用程序要求用户在按下后退按钮以从主屏幕退出我的应用程序时对我的应用程序进行评分。 应该显示一个片段,要求现在或以后对其进行评分。 该片段显示大约1秒钟,然后在用户做出选择之前关闭应用程序。 我该如何解决?

这是我想出的解决方案:

我将向您展示如何实现该片段以及如何防止它绕过片段关闭活动。

在我的主要活动中,我添加了:

@Override
public void onBackPressed() {
     final DialogFragment rate = new RateMe();
   rate.show(getSupportFragmentManager(), "Rate");
}

确保从Override中删除super语句,以在按下后退按钮时完全停止按钮退出您的应用程序。

我使用名为“ RateMe”的xml创建了一个空白片段活动。 删除“ Hllo World”后,我将xml留为空白,但请务必仔细检查您的tools:context =。 这是我犯的一个错误,与我的包裹不符。 简单修复。 只需将其更改为您的包裹名称即可。

然后在片段中输入:

public class RateMe extends DialogFragment {

public static RateMe newInstance(int title) {
    RateMe frag = new RateMe();
    Bundle args = new Bundle();
   // args.putInt("title", title);
    frag.setArguments(args);
    return frag;
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setCancelable(false);
    builder.setTitle("Rate Me");
    builder.setMessage(R.string.Rate);

//在您的res值strings.xml文件中创建一个字符串。 这将是您的//R.string出现在片段上^^^^然后继续添加......

    builder.setPositiveButton("Yes, I Will", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            Uri uri = Uri.pa(RateMe.this);rse("market://details?id=****PUT YOUR GOOGLE PLAY URL INFO HERE");
            Intent myAppLinkToMarket = new Intent(Intent.ACTION_VIEW, uri);
            myAppLinkToMarket.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                    Intent.FLAG_ACTIVITY_NEW_DOCUMENT |
                    Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            try {
                startActivity(myAppLinkToMarket);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getContext(), " unable to find market app", Toast.LENGTH_LONG).show();
            }

        }
    });
    builder.setNegativeButton("Not Now", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            System.exit(0);    //this will close the application
        }
    });
    return builder.create();
}

}

这对我来说非常有效。 希望这可以帮助某人。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM