简体   繁体   English

从非活动类开始新的活动

[英]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: 我有的:

  1. A GridView + a ButtonAdapter class, which also has a OnClickListener class to get wich button on the GridView in pressed. 一个GridView + ButtonAdapter类,该类还具有一个OnClickListener类,以按按下GridView上的按钮。 (you can see the basic structure here : http://www.stealthcopter.com/blog/2010/09/android-creating-a-custom-adapter-for-gridview-buttonadapter/ ) (您可以在这里看到基本结构: http : //www.stealthcopter.com/blog/2010/09/android-creating-a-custom-adapter-for-gridview-buttonadapter/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM