[英]Starting new activity from a non activity class
I know it's been alot of questions like this, but I didn't find the answer. 我知道有很多这样的问题,但是我没有找到答案。
What I have: 我有的:
What I need: 我需要的:
I need to start a new Activity
from my OnClickListener
class. 我需要从OnClickListener
类开始一个新的Activity
。 As I know I can make it only in my main acitivity class(or other class which extends Activity
), but this is what I really need. 据我所知,我只能在我的主要活动性类(或扩展Activity
其他类)中做到这一点,但这是我真正需要的。 I know only this structure: 我只知道这种结构:
Intent i = new Intent(MyMain.this, MyNewActivity.class)
startActivity(i);
I want to be able to use this structure from my OnClickListener
class. 我希望能够从我的OnClickListener
类使用此结构。
In your ButtonAdapter
constructor pass the context of the Activity
where you build the adapter and then use that Context
to start the new Activity
. 在ButtonAdapter
构造函数中,传递在其中构建适配器的Activity
的上下文,然后使用该Context
启动新的Activity
。
Edit: Following that tutorial when you build your adapter you will do something like this: 编辑:在构建适配器时,遵循该教程,您将执行以下操作:
ButtonAdapter adapter = new ButtonAdapter(this);// this is the activity(if you create in an activity the adapter)
The Context
that you get in the constructor of your ButtonAdapter
you will pass it to your OnClickListener
: 在ButtonAdapter
的构造函数中获得的Context
会将其传递给OnClickListener
:
class MyOnClickListener implements OnClickListener
{
private final int position;
private Context ctx;
public MyOnClickListener(int position, Context ctx)
{
this.position = position;
this.ctx = ctx;
}
public void onClick(View v)
{
// Preform a function based on the position
someFunction(this.position)
Intent i = new Intent(MyMain.this, MyNewActivity.class)
ctx.startActivity(i);
}
}
and use it like this: 并像这样使用它:
btn.setOnClickListener(new MyOnClickListener(position, mContext));
由于MyOnClickListener.onClick()中有View对象,因此可以简单地使用View.getContext()(http://developer.android.com/reference/android/view/View.html#getContext())来获取上下文对象并开始另一个活动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.