StartActivity () on RecyclerView
I need to trigger an action based on the element the user clicks on RecyclerView
. The code below has a position as a reference. Does anyone know how to do this? I need something like Intent intent = new Intent (MainActivity.this, Target.class)
. The target class changes depending on the selected item.
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, ???);
startActivity(intent);
}
})
);
You have a collection of objects (maybe an ArrayList), try adding an Object that has a field of type Class and then get it like this:
Intent intent = new Intent(MainActivity.this, objects.get(position).getClassField());
startActivity(intent);
Well, how about just putting the correct OnClickListener on every View item in the RecyclerView? Each OnClickListener can store the target class needed to handle navigation. You can handle this in the binding phase of the RecyclerView adapter, there is no magic there.
Select target class via position
:
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(this, new RecyclerItemClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
switch(position){
case 0:
startActivity(new Intent(MainActivity.this, A.class));
break;
case 1:
startActivity(new Intent(MainActivity.this, B.class));
break;
default:
break;
}
}
})
);
Of course, you need to define the mapping from position
to target class
.
You just need to put onclicklistener in your viewer (contain views).
private MainActivity mAct;
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAct.animateActivity(anything);
}
});
public void animateActivity(anything any) {
Intent i = new Intent(this, AssetDescription.class);
//Some anitmation if you want
startActivity(i);
}