Comment ouvrir une autre activité sur recyclerView article onclick

j'utilise un recyclerView pour montrer mon listitems dans le navigation drawer.J'ai implémenté le onclickListener mais j'ai été coincé sur la façon d'ouvrir un autre activity quand élémentsclicked. Tous mes articles font sur le clic d'article dès maintenant que selon le code est d'afficher un toastitem position.

je vous serais reconnaissant de l'aide.

AdapterClass.java

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}
Log  cat error after implementing Konrad's solution

    02-27 15:24:52.833: D/AndroidRuntime(1630): --------- beginning of crash
02-27 15:24:52.834: E/AndroidRuntime(1630): FATAL EXCEPTION: main
02-27 15:24:52.834: E/AndroidRuntime(1630): Process: com.snappy.stevekamau.snappy, PID: 1630
02-27 15:24:52.834: E/AndroidRuntime(1630): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.snappy.stevekamau.snappy/com.snappy.stevekamau.snappy.YourActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.access0(ActivityThread.java:144)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.os.Looper.loop(Looper.java:135)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.main(ActivityThread.java:5221)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Native Method)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at java.lang.reflect.Method.invoke(Method.java:372)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
02-27 15:24:52.834: E/AndroidRuntime(1630): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:95)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.widget.ToolbarWidgetWrapper.<init>(ToolbarWidgetWrapper.java:88)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.internal.app.ToolbarActionBar.<init>(ToolbarActionBar.java:84)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivityDelegateBase.setSupportActionBar(ActionBarActivityDelegateBase.java:175)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.support.v7.app.ActionBarActivity.setSupportActionBar(ActionBarActivity.java:92)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at com.snappy.stevekamau.snappy.YourActivity.onCreate(YourActivity.java:18)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Activity.performCreate(Activity.java:5933)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-27 15:24:52.834: E/AndroidRuntime(1630):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
02-27 15:24:52.834: E/AndroidRuntime(1630):     ... 10 more
02-27 15:24:52.839: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.YourActivity
02-27 15:24:52.841: W/ActivityManager(464):   Force finishing activity com.snappy.stevekamau.snappy/.MainActivity
33
demandé sur cricket_007 2015-02-27 17:29:55

6 réponses

Vous pouvez (mais n'en a pas besoin parce que l' ViewHolder classe n'est pas statique) créer le champ contexte comme il est indiqué ci-dessous:

private final Context context;

public MyViewHolder(View itemView) {
    super(itemView);
    context = itemView.getContext();
    ...
}

et onClick méthode d'appel qqch comme ci-dessous:

@Override
public void onClick(View v) {          

    final Intent intent;
    switch (getAdapterPostion()){
        case 0:
           intent =  new Intent(context, FirstActivity.class);
           break;

        case 1:
            intent =  new Intent(context, SecondActivity.class);
            break;
           ...
        default:
           intent =  new Intent(context, DefaultActivity.class);
           break;
     }
    context.startActivity(intent);
}

ou

@Override
public void onClick(View v) {          

    final Intent intent;
    if (getAdapterPosition() == sth){
       intent =  new Intent(context, OneActivity.class);
    } else if (getPosition() == sth2){
       intent =  new Intent(context, SecondActivity.class);
    } else {
       intent =  new Intent(context, DifferentActivity.class);
    }
    context.startActivity(intent);
}
70
répondu Konrad Krakowiak 2018-02-16 04:26:17

vous pouvez implémenter le onClickListener de votre adaptateur:

  public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener

et l'utilisation de l'interface avec la méthode en elle

public interface mClickListener {
    public void mClick(View v, int position);
}

et dans ton onClick appel de la méthode la méthode dans l'interface et de passer de la vue et la position

dans votre activité principale implémentez cette interface

public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener

et de remplacer cette méthode

@Override
public void onCommentsClick(View v, int position) {
    final Intent intent = new Intent(this, OtherActivity.class);
}

comme il vaut mieux gérer votre transition d'activité par l'Activité pas d'autres classes

2
répondu mohab elmahdy 2017-04-09 03:29:06

cette question a été posée il y a longtemps, de toute façon j'écrirais une réponse facile puisse-t-elle aider quelqu'un.

la façon la plus facile d'attacher un clickListener à des articles de RecyclerView est à L'intérieur de L'adaptateur comme ci-dessous:

 @Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getContext() , yourActivity.Class)
               startActivity(intent);
            }
        });

}
2
répondu Milad Moosavi 2017-11-18 15:14:38

Simplement, vous pouvez le faire facilement... Vous devez juste obtenir le contexte de votre activité, ici, de votre point de vue.

//Create intent getting the context of your View and the class where you want to go
Intent intent = new Intent(view.getContext(), YourClass.class);

//start the activity from the view/context
view.getContext().startActivity(intent); //If you are inside activity, otherwise pass context to this funtion

rappelez-vous que vous devez modifier AndroidManifest.xml et placer l'activité...

<activity
        android:name=".YourClass"
        android:label="Label for your activity"></activity>
1
répondu Dani Gee 2017-11-16 14:58:32
  • Exemple,MyRecyclerViewAdapter, ajoutez la méthode:

    public interface ItemClickListener {
       void onItemClick(View view, int position);
    }
    
  • MainActivity.java

    @Override
    public void onItemClick(View view, int position) {
    Context context=view.getContext();
    Intent intent=new Intent();
    switch (position){
        case 0:
            intent =  new Intent(context, ChildActivity.class);
            context.startActivity(intent);
            break;
       }
    }
    
1
répondu O Thạnh Ldt 2018-01-03 09:06:06

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}

public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
    private LayoutInflater inflater;
    private Context context;
List<Information>data= Collections.emptyList();
    public AdapterClass(Context context,List<Information>data){
        this.context=context;

        inflater= LayoutInflater.from(context);
        this.data=data;
    }
    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       View view= inflater.inflate(R.layout.custom_row,parent,false);
        MyViewHolder holder=new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        Information current=data.get(position);
        holder.title.setText(current.title);
        holder.icon.setImageResource(current.iconId);

    }

    @Override
    public int getItemCount() {
        return data.size();
    }
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        TextView title;
        ImageView icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.listText);
           icon=(ImageView)itemView.findViewById(R.id.listIcon);
            itemView.setClickable(true);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {

            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();
        }
    };
}
0
répondu raju dhiraj 2018-06-09 07:54:29