Class 变量在 onCreateDialog 中不维护它的值

Class variable does not maintain its value in onCreateDialog

我已经为我在 我的应用程序。我还有一个未知类型(泛型)的数组列表 值取决于静态数组列表来自哪个 activity。在 为了区分 activity 静态数组列表的来源,我使用 布尔 class 变量。令我惊讶的是这个布尔变量,虽然 在 newInstance(Context c, int dialogNumber) 方法中获取它的值,在 onCreateDialog 方法它获取默认的布尔值,即 false。

非常感谢任何帮助。

这是 DialogFragmentHelper class' 代码:

public class DialogFragmentHelper extends DialogFragment {

private static final ArrayList<FoodRecord> allRecords = FoodActivity.allRecords;
private static final ArrayList<BgRecord> mBgRecords = MainActivity.mBgRecords;
private static ArrayList<?> mRecords;
private int dNumber;
private Context mContext;
private boolean fromFoodActivity;


public DialogFragmentHelper newInstance(Context context, int dialogNumber) {
    mContext = context;
    if(mContext instanceof FoodActivity || mContext instanceof FoodExpandableListActivity) {
        fromFoodActivity = true;
        mRecords = allRecords;
    }
    else {
        fromFoodActivity = false;
        mRecords = mBgRecords;
    }
    DialogFragmentHelper mDialogFragment = new DialogFragmentHelper();

    // Supply dialogNumber input as an argument
    Bundle args = new Bundle();
    args.putInt(DIALOG_NUMBER_KEY, dialogNumber);
    mDialogFragment.setArguments(args);

    return mDialogFragment;
}


// Build AlertDialog using AlertDialog.Builder
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    dNumber = getArguments().getInt(DIALOG_NUMBER_KEY);

    AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
    LayoutInflater inflater = getActivity().getLayoutInflater();
    Button okButton;
    Button cancelButton;


    switch(dNumber) {
    case CHOOSE_DATES_DIALOG_FULL_HISTORY:
        if(mRecords != null && mRecords.size() != 0) {
            adb.setView(inflater.inflate(R.layout.choose_dates_dialog, null))
            .setCancelable(true)
            .create();

            AlertDialog customChooseDialog = adb.show();
            if(fromFoodActivity) { //here fromFoodActivity is false
                TextView mTitle = (TextView) customChooseDialog.findViewById(R.id.title);
                mTitle.setText(R.string.food_activity_log);
            }
        }
     ....    
     }

在各自的活动中,我这样调用 DialogFragmentHelper class:

DialogFragmentHelper af = new DialogFragmentHelper();
mDialog = af.newInstance(this, CHOOSE_DATES_DIALOG);
mDialog.show(getFragmentManager(), "Choose");

这是因为在 newInstance() 方法中您创建了一个全新的 DialogFragmentHelper 实例,其 fromFoodActivity 的默认值为 false.

整个建筑有点邪恶。 "Helpers" 通常需要访问主对象,但这里有一个助手帮助创建一个助手。

无论如何,作为快速修复,您可以为这个新实例设置 fromFoodActivity

mDialogFragment.fromFoodActivity = fromFoodActivity;