Intent is not working in my RecyclerView

后端 未结 4 832
被撕碎了的回忆
被撕碎了的回忆 2021-01-27 00:17

I use this code:

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater         


        
相关标签:
4条回答
  • 2021-01-27 00:46

    Probably context is null try it as:

     public void onClick(View v) {
        Intent myIntent = new Intent(v.getContext(), MainActivity2Activity.class);
         v.getContext().startActivity(myIntent);
      }
    
    0 讨论(0)
  • 2021-01-27 00:54

    AFAIK, RecyclerView doesn't support click events of child views of items. Any events of child views are shielded. Only RecyclerView.OnItemTouchListener is OK to listen to events of items of RecyclerView.

    0 讨论(0)
  • 2021-01-27 01:00

    In the following code I feel context is null hence you get the error change the following code:

    public void onClick(View v) {
                    Intent myIntent = new Intent(context, MainActivity2Activity.class);
                    context.startActivity(myIntent);
                }
    

    change the above code to:

    public void onClick(View v) {
                    Intent myIntent = new Intent(getApplicationContext(), MainActivity2Activity.class);
                    context.startActivity(myIntent);
                }
    

    or

    public void onClick(View v) {
                    Intent myIntent = new Intent(getBaseContext, MainActivity2Activity.class);
                    context.startActivity(myIntent);
                }
    

    I feel what you are doing is not correct to use onClicks you need to set an interface as shown below:

    @Override
            public void onClick(View view) {
    
                if (clickListener != null) {
                    clickListener.itemClicked(view, getPosition());
                }
    
            }
    
    public interface ClickListener {
    
            public void itemClicked(View view, int position);
        }
    

    Now you need to implement the interface in your activity that will work fine. Try this.

    Hope this helps.

    0 讨论(0)
  • 2021-01-27 01:06

    Hi call your adapter such like this way :

     adapter = new MyAdapter(MainActivity.this,people);
     recyclerView.setAdapter(adapter);
    

    You can also get the view.getContext() inside you button onClick listener.

    I hope it can help you to resolved the problem. thank you.

    0 讨论(0)
提交回复
热议问题