如何在片段构造函数中获取父活动引用?

时间:2015-06-19 12:34:57

标签: android android-fragments

我的SELECT * FROM mytable WHERE datefield >= '20140101' AND datefield < '20150101' GameActivity方法之一是:

Activity

这是方法创建的对话框片段:

/** Show "Game is finished" dialog. */
public void showFinishedDlg(int bodyMsgRes) {
    GameFinishedDlgFragment.newInstance(bodyMsgRes).show(
            this.getFragmentManager(), "finished_dlg");
}

我试图让对话框的public class GameFinishedDlgFragment extends DialogFragment { static GameFinishedDlgFragment newInstance(int bodyMsgRes) { GameFinishedDlgFragment frag = new GameFinishedDlgFragment(); Bundle bundle = new Bundle(); bundle.putInt("body_msg", bodyMsgRes); frag.setArguments(bundle); return frag; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); int bodyMsgRes = args.getInt("body_msg"); // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(bodyMsgRes) .setPositiveButton(R.string.new_game, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // PROBLEM HERE. TODO: Restart GameActivity this.parentActivity.recreate(); } }); // Create the AlertDialog object and return it return builder.create(); } } 按钮重新启动onClick,但我无法弄清楚如何获取对该活动实例的引用

如果我尝试:

GameActivity

编译告诉我:

this.parentActivity.recreate();

3 个答案:

答案 0 :(得分:2)

放手一搏:

getActivity().recreate();

答案 1 :(得分:1)

var mongoose = require('mongoose'),
    groupid = mongoose.Types.ObjectId(req.headers['groupid']);

答案 2 :(得分:1)

请覆盖片段的onAttach方法。 传入的活动参数是您的父活动。

片段的生命周期方法: http://developer.xamarin.com/guides/android/platform_features/fragments/part_1_-_creating_a_fragment/Images/fragment_lifecycle.png

官方参考: http://developer.android.com/reference/android/app/DialogFragment.html#onAttach(android.app.Activity)

或者只是在你编码的任何地方调用getActivity(),onAttach完成后!在onAttach之前调用它,它给出了NULL

(阅读以下评论)