Java 如何在适配器中启动 Activity?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4197135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:28:40  来源:igfitidea点击:

How to start Activity in adapter?

javaandroidandroid-activityadapter

提问by justicepenny

I have a ListActivity with my customized adapter and inside each of the view, it may have some buttons, in which I need to implement OnClickListener. I need to implement the OnClickListenerin the adapter. However, I don't know how to call the function like startActivity()or setResult(). Since the adapter doesn't extend to Activity.

我有一个带有自定义适配器的 ListActivity 并且在每个视图中,它可能有一些按钮,我需要在其中实现OnClickListener. 我需要OnClickListener在适配器中实现。但是,我不知道如何调用像startActivity()or之类的函数setResult()。由于适配器没有扩展到 Activity。

So what is the best way to solve this problem?

那么解决这个问题的最佳方法是什么?

Thanks.

谢谢。

采纳答案by Robby Pond

Just pass in the current Context to the Adapter constructor and store it as a field. Then inside the onClick you can use that context to call startActivity().

只需将当前 Context 传递给 Adapter 构造函数并将其存储为字段。然后在 onClick 中,您可以使用该上下文来调用 startActivity()。

pseudo-code

伪代码

public class MyAdapter extends Adapter {
     private Context context;

     public MyAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

回答by ccheneson

When implementing the onClickListener, you can use v.getContext.startActivity.

实现 时onClickListener,您可以使用v.getContext.startActivity.

btn.setOnClickListener(new OnClickListener() {                  
    @Override
    public void onClick(View v) {
        v.getContext().startActivity(PUT_YOUR_INTENT_HERE);
    }
});

回答by edwin

public class MyAdapter extends Adapter {
     private Context context;      


     public MyAdapter(Context context) {
          this.context = context;         
     }


     public View getView(...){  
         View v;  
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                  Intent intent= new Intent(context, ToActivity.class); 
                   intent.putExtra("your_extra","your_class_value");
                 context.startActivity(intent);
             }
         });
     }
}

回答by DevKRos

callback from adapter to activity can be done using registering listener in form of interface: Make an interface:

可以使用以接口形式注册侦听器来完成从适配器到活动的回调:创建一个接口:

      public MyInterface{
         public void  yourmethod(//incase needs parameters );
         }

In Adapter Let's Say MyAdapter:

在适配器中让我们说 MyAdapter:

    public MyAdapter extends BaseAdapter{
       private MyInterface listener;

    MyAdapter(Context context){
        try {
            this. listener = (( MyInterface ) context);
              } catch (ClassCastException e) {
               throw new ClassCastException("Activity must implement MyInterface");
          }

//do this where u need to fire listener l

//在需要触发监听器的地方执行此操作

          try {
                listener . yourmethod ();
            } catch (ClassCastException exception) {
               // do something
            }

      In Activity Implement your method:


         MyActivity extends AppCompatActivity implements MyInterface{

                yourmethod(){
                //do whatever you want
                     }
                     }

回答by Kamran

For newer versions of sdk you have to set flag activity task.

对于较新版本的 sdk,您必须设置标志活动任务。

public void onClick(View v)
 {
     Intent myactivity = new Intent(context.getApplicationContext(), OtherActivity.class);
     myactivity.addFlags(FLAG_ACTIVITY_NEW_TASK);
     context.getApplicationContext().startActivity(myactivity);
 }

回答by Nimesh Patel

If you want to redirect on url instead of activity from your adapter class then pass context of with startactivity.

如果您想重定向 url 而不是来自您的适配器类的活动,请传递 with startactivity 的上下文。

btnInstall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse(link));
                intent.setData(Uri.parse(link));
                context.startActivity(intent);
            }
        });

回答by sheraz Ahmed

Simple way to start activity in Adopter's button onClickListener:

在采用者的按钮 onClickListener 中启动活动的简单方法:

Intent myIntent = new Intent(view.getContext(),Event_Member_list.class);                    myIntent.putExtra("intVariableName", eventsList.get(position).getEvent_id());
                view.getContext().startActivity(myIntent);

回答by Masoud Mokhtari

First Solution:

第一个解决方案:

You can call start activity inside your adapter like this:

您可以在适配器内调用 start 活动,如下所示:

public class YourAdapter extends Adapter {
     private Context context;

     public YourAdapter(Context context) {
          this.context = context;     
     }

     public View getView(...){
         View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 context.startActivity(...);
             }
         });
     }
}

Second Solution:

第二种解决方案:

You can call onClickListenerof your button out of the YourAdapterclass. Follow these steps:

你可以onClickListenerYourAdapter课堂外调用你的按钮。按着这些次序:

Craete an interface like this:

创建一个这样的界面:

public YourInterface{
         public void  yourMethod(args...);
}

Then inside your adapter:

然后在你的适配器里面:

    public YourAdapter extends BaseAdapter{
               private YourInterface listener;

           public YourAdapter (Context context, YourInterface listener){
                    this.listener = listener;
                    this.context = context;
           }

           public View getView(...){
                View v;
         v.setOnClickListener(new OnClickListener() {
             void onClick() {
                 listener.yourMethod(args);
             }
         });
}

And where you initiate yourAdapter will be like this:

您启动 yourAdapter 的位置将如下所示:

YourAdapter adapter = new YourAdapter(getContext(), (args) -> {
            startActivity(...);
        });

This linkcan be useful for you.

链接可能对您有用。