我为我所有的对话片段制作了一个DialogFragment助手类 我的应用。我也有一个未知类型的arraylist(泛型)得到它 值取决于静态arraylist来自哪个活动。在 为了区分静态arraylist来自的活动,我使用 布尔类变量。令我惊讶的是这个布尔变量 在newInstance(Context c,int dialogNumber)方法中获取其值 onCreateDialog方法,它获取默认的布尔值,即false。
任何帮助都将受到高度赞赏。
这是DialogFragmentHelper类的代码:
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类:
DialogFragmentHelper af = new DialogFragmentHelper();
mDialog = af.newInstance(this, CHOOSE_DATES_DIALOG);
mDialog.show(getFragmentManager(), "Choose");
答案 0 :(得分:1)
这是因为在newInstance()
方法内部,您创建了一个全新的DialogFragmentHelper
实例,其默认值fromFoodActivity
为false
。
整个建筑有点邪恶。通常需要“帮助者”来访问主要对象,但是帮助者可以帮助创建帮助者。
无论如何,作为快速修复,您可以为此新实例设置fromFoodActivity
:
mDialogFragment.fromFoodActivity = fromFoodActivity;