【问题标题】:How to use FragmentManager to substitute the deprecated showDialog如何使用 FragmentManager 替换已弃用的 showDialog
【发布时间】:2012-10-03 13:57:37
【问题描述】:

我正在使用方法 displayDialog... 它可以工作,但 Eclipse 对此显示警告:

showDialog(showRetry ? 1 : 0);

方法:

   private void displayDialog(final boolean showRetry) {
                    mHandler.post(new Runnable() {
                        public void run() {
                            setProgressBarIndeterminateVisibility(false);
                            showDialog(showRetry ? 1 : 0);
                        }
                    });
                } 

搜索我发现了类似的问题,其中看到现在有 FragmentManager 可以用来避免这个问题,但我不明白如何用它来解决我的问题与 Froyo 和 GingerBread 保持追溯兼容性的特定场景。

你能帮帮我吗?

完整的类代码是:

 public class Home extends Activity {
        private static final String BASE64_PUBLIC_KEY = "mykeywithoutspaces";

        // Generate your own 20 random bytes, and put them here.
        private static final byte[] SALT = new byte[] {
            -00, 00, 30, -2, -58, -57, 00, -64, 51, 32, -95, -45, 13, -6, -36, -15, -11, 32, -64,
            89
        };

        private TextView mStatusText;
        private Button mCheckLicenseButton;

        private LicenseCheckerCallback mLicenseCheckerCallback;
        private LicenseChecker mChecker;
        // A handler on the UI thread.
        private Handler mHandler;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
            setContentView(R.layout.main);

            mStatusText = (TextView) findViewById(R.id.status_text);
buttonNewDoc = (ImageButton) findViewById(R.id.btNewDoc);
        buttonNewDoc.setOnClickListener(mNewDoc);
            mCheckLicenseButton = (Button) findViewById(R.id.check_license_button);
            mCheckLicenseButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    doCheck();
                }
            });

            mHandler = new Handler();

            // Try to use more data here. ANDROID_ID is a single point of attack.
            String deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);

            // Library calls this when it's done.
            mLicenseCheckerCallback = new MyLicenseCheckerCallback();
            // Construct the LicenseChecker with a policy.
            mChecker = new LicenseChecker(
                this, new ServerManagedPolicy(this,
                    new AESObfuscator(SALT, getPackageName(), deviceId)),
                BASE64_PUBLIC_KEY);
            doCheck();
        }

        protected Dialog onCreateDialog(int id) {
            final boolean bRetry = id == 1;
            return new AlertDialog.Builder(this)
                .setTitle(R.string.unlicensed_dialog_title)
                .setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
                .setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
                    boolean mRetry = bRetry;
                    public void onClick(DialogInterface dialog, int which) {
                        if ( mRetry ) {
                            doCheck();
                        } else {
                            Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                    "http://market.android.com/details?id=" + getPackageName()));
                                startActivity(marketIntent);                        
                        }
                    }
                })
                .setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).create();
        }

        private void doCheck() {
buttonNewDoc.setEnabled(false);
            mCheckLicenseButton.setEnabled(false);
            setProgressBarIndeterminateVisibility(true);
            mStatusText.setText(R.string.checking_license);
            mChecker.checkAccess(mLicenseCheckerCallback);
        }

        private void displayResult(final String result) {
            mHandler.post(new Runnable() {
                public void run() {
                    mStatusText.setText(result);
                    setProgressBarIndeterminateVisibility(false);
                    mCheckLicenseButton.setEnabled(true);
                }
            });
        }

        private void displayDialog(final boolean showRetry) {
            mHandler.post(new Runnable() {
                public void run() {
                    setProgressBarIndeterminateVisibility(false);
                    showDialog(showRetry ? 1 : 0);
                }
            });
        }    

        private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
            public void allow(int policyReason) {
                if (isFinishing()) {
                    // Don't update UI if Activity is finishing.
                    return;
                }

                // Should allow user access.
                displayResult(getString(R.string.allow));
buttonNewDoc.setEnabled(false);
            }

            public void dontAllow(int policyReason) {
                if (isFinishing()) {
                    // Don't update UI if Activity is finishing.
                    return;
                }
                displayResult(getString(R.string.dont_allow));
                // Should not allow access. In most cases, the app should assume
                // the user has access unless it encounters this. If it does,
                // the app should inform the user of their unlicensed ways
                // and then either shut down the app or limit the user to a
                // restricted set of features.
                // In this example, we show a dialog that takes the user to Market.
                // If the reason for the lack of license is that the service is
                // unavailable or there is another problem, we display a
                // retry button on the dialog and a different message.
                displayDialog(policyReason == Policy.RETRY);
            }

            public void applicationError(int errorCode) {
                if (isFinishing()) {
                    // Don't update UI if Activity is finishing.
                    return;
                }
                String result = String.format(getString(R.string.application_error), errorCode);
                displayResult(result);
            }
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            mChecker.onDestroy();
        }

    }

【问题讨论】:

    标签: android android-fragments deprecated


    【解决方案1】:

    科特林:

    requireActivity().supportFragmentManager
    

    【讨论】:

    • 解决了从java转换为kotlin后的问题。
    【解决方案2】:

    您的活动应该是FragmentActivity 的子类,可以在v4 support library 中找到,您应该将其添加到您的项目中。然后,您可以使用getSupportFragmentManager() 获得对FragmentManager 的引用以显示DialogFragment。您必须使用对话框所需的布局和逻辑创建一个DialogFragment 类。以下是您在FragmentActivity 中的展示方式:

    FragmentManager fm = getSupportFragmentManager();
    YourDialogFragment yourDialog = new YourDialogFragment();
    yourDialog.show(fm, "some_optional_tag");
    

    这里是一个概述:http://android-developers.blogspot.com/2012/05/using-dialogfragments.html

    【讨论】:

    • 感谢您的回答。但是我很难在课堂上正确完成这些任务......你能写更多代码吗?谢谢。
    • 你看到安卓博客的链接了吗?这是一个非常全面的分步指南,包含您可能需要的所有代码...
    【解决方案3】:

    谷歌在这个例子中似乎使用的是更改“受保护的对话框 onCreateDialog (int id) {”,以便始终在内部调用它,称为“showDialog (showRetry?1:0);”为重试/取消创建默认对话框。

    我建议使用以下代码,创建一个方便的方法来创建标准对话框,并更改或删除“onCreateDialog()”,因为这变得不必要了。

    protected Dialog onCreateDialog(int id) {
        return CreateDialogRetryCancel(id);
    }
    
    public Dialog CreateDialogRetryCancel(int id) {
        final boolean bRetry = id == 1;
        return new AlertDialog.Builder(this)
            .setTitle(R.string.unlicensed_dialog_title)
            .setMessage(bRetry ? R.string.unlicensed_dialog_retry_body : R.string.unlicensed_dialog_body)
            .setPositiveButton(bRetry ? R.string.retry_button : R.string.buy_button, new DialogInterface.OnClickListener() {
                boolean mRetry = bRetry;
                public void onClick(DialogInterface dialog, int which) {
                    if ( mRetry ) {
                        doCheck();
                    } else {
                        Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
                                "http://market.android.com/details?id=" + getPackageName()));
                            startActivity(marketIntent);                        
                    }
                }
            })
            .setNegativeButton(R.string.quit_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            }).create();
    }
    
    private void displayDialog(final boolean showRetry) {
        mHandler.post(new Runnable() {
            public void run() {
                setProgressBarIndeterminateVisibility(false);
                CreateDialogRetryCancel(showRetry ? 1 : 0).show();
                //showDialog(showRetry ? 1 : 0);
                mCheckLicenseButton.setEnabled(true);
            }
        });
    }    
    

    【讨论】:

      【解决方案4】:
      FragmentManager fm = getSupportFragmentManager();
      yourDialog.show(fm, "some_optional_tag");
      

      getSupportFragmentManager() 仅在制作 DialogFragment 时导入正确的类时才被接受,即 import android.support.v4.app.DialogFragment

      【讨论】:

        猜你喜欢
        • 2020-02-27
        • 2018-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多