Android: startActivity() from AlertDialog

眉间皱痕 提交于 2020-01-02 14:50:34

问题


I am trying to use a Button in an AlertDialog to view a webpage.

The problem is that this AlertDialog is located inside a class that extends ItemizedOverlay and doesn't extend Activity, so Eclipse underlines it and gives the following error:

The method startActivity() is undefined for the type new DialogInterface.OnClickListener(){}

I would like to launch activities from the PositiveButton, NeutralButton and NegativeButton, but I am not able to.

In case you need more context, the main Activity is a MapView with some ItemizedOverlay, and I would like to launch a webpage with directions or another activity that does that.


回答1:


Construct a constructor in the class which contains your alert with Context object as a parameter. Assign it to a Context variable.

Use this context variable for creating the intent.

Intent intent = new Intent(mContext, "Your next activity to be shown");//mContext is the Context variable over here.
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    
mContext.startActivity(intent);



回答2:


Actually the answer is provided by you in your question. i.e startActivity is undefined in ClickListener functions. so in oncreate function, initialize a Global variable like

Activity myActivity = this;

then in onclicklistener, start another activity from this.

myActivity.startActivity(xxxxxxxx);

This could be one answer.




回答3:


Take a look at this

In these you write your desired code inside the Positive Button,You can start an Activity by using Intent..

startActivity(new Intent (YouPage.this,NewPage.class));



回答4:


Pass context of the activity in constructor of that class and create a field of type activity and store context in that activity and then

say

Activity activityClass;

and initialize it from your constructor

and start activity from that activiytClass

activityClass.startActivity();




回答5:


If you have the context say context.startActivity();

if you dont have context try to get it from getContext(); or getApplicationContext(); or getBaseContext();



来源:https://stackoverflow.com/questions/5297687/android-startactivity-from-alertdialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!