getActivity() where it is defined?

2020-02-08 01:02发布

I'm very new to android and I'm following this example.

The code says we need to do these steps to get an dialog box:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.dialog_message)
       .setTitle(R.string.dialog_title);

// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();

But where does the getActivity() method is defined?

I can't find that method.

11条回答
对你真心纯属浪费
2楼-- · 2020-02-08 01:20

getActivity(); is a method of android Fragment, if you want to show dialog in your activity, just pass this of your activity instead of getActivity().

查看更多
疯言疯语
3楼-- · 2020-02-08 01:22

I had exactly the same problem and finally I found what I actually suspected... Simply add:

dialog.show();

...and voila. There it is. Wonder why this isn't stated in the original example!?

查看更多
劳资没心,怎么记你
4楼-- · 2020-02-08 01:32

getActivity() is implemented in the Fragment class.

See http://developer.android.com/reference/android/app/Fragment.html

查看更多
迷人小祖宗
5楼-- · 2020-02-08 01:33

new AlertDialog.Builder() needs Context as input parameter. So try like

AlertDialog.Builder builder = new AlertDialog.Builder(yourActivityName.this);
查看更多
贼婆χ
6楼-- · 2020-02-08 01:35

// 1. Instantiate an AlertDialog.Builder with its constructor

AlertDialog.Builder builder = new AlertDialog.Builder(yourActivityName.this);

// 2. Chain together various setter methods to set the dialog characteristics

builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);

// 3. Get the AlertDialog from create()

AlertDialog dialog = builder.create();

// 4. Show the AlertDialog

dialog.show();
查看更多
等我变得足够好
7楼-- · 2020-02-08 01:37

Update android API level 23.

Use getContext() instead of getActivity().

查看更多
登录 后发表回答