j'utilise un recyclerView
pour afficher mon listitems
dans le navigation drawer
. J'ai implémenté le onclickListener
mais j'ai été bloqué sur la façon d'ouvrir un activity
différent lorsque items are clicked
. Tous mes articles font un clic sur un élément à partir de maintenant, conformément au code, pour afficher un toast
avec le item 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.access$800(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
Vous pouvez (mais vous n’en avez pas besoin car la classe ViewHolder
n’est pas statique) pour créer un contexte de champ comme indiqué ci-dessous:
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
...
}
et sur votre méthode onClick
, appelez simplement sth 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);
}
Cette question a été posée il y a longtemps, de toute façon, j'écrirais une réponse simple, cela aiderait-il quelqu'un.
Le moyen le plus simple de joindre un clickListener aux éléments de RecyclerView consiste à utiliser l'adaptateur, comme indiqué ci-dessous:
public class MyAdapter extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {
....
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), YourActivity.Class);
startActivity(intent);
}
});
}
vous pouvez implémenter onClickListener de votre adaptateur:
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder>implements View.OnClickListener
et utiliser l'interface avec la méthode en elle
public interface mClickListener {
public void mClick(View v, int position);
}
et dans votre méthode onClick appelez la méthode dans l'interface et passez-la à la vue et à la position
dans votre activité principale implémenter cette interface
public class MainActivity extends ActionBarActivity implements AdapterClass.mClickListener
et surcharger 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
Simplement, vous pouvez le faire facilement ... Il vous suffit de connaître le contexte de votre activité, ici, depuis votre 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
N'oubliez pas que vous devez modifier AndroidManifest.xml et placer l'activité ...
<activity
Android:name=".YourClass"
Android:label="Label for your activity"></activity>
Exemple, dans MyRecyclerViewAdapter , méthode add:
public interface ItemClickListener {
void onItemClick(View view, int position);
}
Dans 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;
}
}
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<Android> Android;
Context context;
private ImageView img;
public DataAdapter(Context contextN, ArrayList<Android> Android) {
this.Android = Android;
this.context=contextN;
}
@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.adapter_list, viewGroup, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(DataAdapter.ViewHolder viewHolder, int i) {
viewHolder.tv_name.setText(Android.get(i).getOffer());
viewHolder.tv_version.setText(Android.get(i).getOfferType());
Picasso.with(context).load(Android.get(i).getImg()).transform(new CircleTransform()).into(img);
}
@Override
public int getItemCount() {
return Android.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private TextView tv_name,tv_version,tv_api_level;
public ViewHolder(View view) {
super(view);
tv_name = (TextView)view.findViewById(R.id.tv_name);
tv_version = (TextView)view.findViewById(R.id.tv_version);
img = (ImageView) view.findViewById(R.id.img);
context = itemView.getContext();
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int itemPosition = getLayoutPosition();
Toast.makeText(context, "" + itemPosition, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,Show.class);
intent.putExtra("name",""+Android.get(itemPosition).getOffer());
intent.putExtra("img",""+Android.get(itemPosition).getImg());
context.startActivity(intent);
}
});
}
}
}
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();
}
};
}