通过findFragmentByTag从FragmentManager获取DialogFragment

Mar*_*tin 5 android dialog android-asynctask android-fragments

我已经通过DialogFragment创建了一个进度对话框,为此我已经使用这篇文章作为我的DialogFragment的基础:https://gist.github.com/daichan4649/6421407 实际上在我的应用程序中我有一个调用类和这个类使用AsyncTask来复制在sqlite数据库中保存一些数据.我使用进度对话框来显示AsyncTask进度.

我的代码有效,但是有一个小问题:当用户旋转设备时,进度条不再更新,因为findFragmentByTag返回始终为null.

这是我的一小段代码.我认为问题在于:

public class TafData {

private Context mContext;

public TafDownload(Context context) {

    mContext = context;
}

... other code ...

private class importTAFAsync extends AsyncTask <String, Integer, String> {
    ... other code ...
}

private void showProgress() {
    TafActivity tafactivity = (TafActivity) mContext;
    FragmentManager fm = tafactivity.getFragmentManager();
    ProgressDialogFragment pDialog = ProgressDialogFragment.newInstance("Caricamento TAF", "Caricamento in corso. Attendere...", 100);
    pDialog.show(fm, "fragment_progress");
}

private void setMax(Integer... values) {
    ProgressDialogFragment progress = getProgressDialogFragment();
    if (progress == null) {
        return;
    }
    progress.setMax(values[0]);
}

private void updateProgress(Integer... values) {
    ProgressDialogFragment progress = getProgressDialogFragment();
    if (progress == null) {
        return;
    }
    progress.updateProgress(values[0]);
}

private void hideProgress() {
    ProgressDialogFragment progress = getProgressDialogFragment();
    if (progress == null) {
        return;
    }
    progress.dismissAllowingStateLoss();
}

private ProgressDialogFragment getProgressDialogFragment() {
    TafActivity tafactivity = (TafActivity) mContext;

    Fragment fragment = tafactivity.getFragmentManager().findFragmentByTag("fragment_progress");
    return (ProgressDialogFragment) fragment;
}
}
Run Code Online (Sandbox Code Playgroud)

这是一个清单:

<activity
    android:name="com.myapp.TafActivity"
    android:label="@string/title_activity_taf">
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="myapp.MapsActivity" />
</activity>
Run Code Online (Sandbox Code Playgroud)

JDJ*_*JDJ -1

将此行添加到 AndroidManifest.xml 中的 TafActivity 声明中:

android:configChanges="orientation|keyboardHidden" 
Run Code Online (Sandbox Code Playgroud)

这将防止系统在方向改变时破坏您的活动。

  • 在调用 findFragmentByTag 之前,请尝试执行以下操作:`FragmentManager fm = tafactivity.getFragmentManager();` fm.executePendingTransactions();` (2认同)