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. 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. 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.
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
.
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
:
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())来获取上下文对象并开始另一个活动。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.