In my recycler view item I have a button so when user clicks on button user is going from one activity to another.
BUt when user is coming back from another activity and presses android back button then it backtracks activity on which recycler view is present.
Here is my code:
public class HomeBookAdapter extends RecyclerView.Adapter<HomeBookAdapter.ViewHolder> {
ArrayList<LoadHomeBooks> list;
Context context;
public HomeBookAdapter(ArrayList<LoadHomeBooks> list,Context context){
this.list = list;
this.context = context;
}
#NonNull
#Override
public HomeBookAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.home_book_layout,viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull final HomeBookAdapter.ViewHolder viewHolder, int i) {
LoadHomeBooks model = list.get(i);
final String bookId = model.getbUid();
viewHolder.homeMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context,BookDetail.class);
i.putExtra("bId",bookId);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
Button homeMore;
public ViewHolder(#NonNull View itemView) {
super(itemView);
homeMore = itemView.findViewById(R.id.homeMore);
}
}
}
Someone please let me know what I am doing wrong.
THANKS
Add this
Intent i = new Intent(context,BookDetail.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(i);
Related
Hello guys, someone can help me to finish this simple project, please?
I don't know how to configure the click on the items for opening a new activities.
RecycleViewAdapter.java
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<ModelData> users;
private Context context;
public RecyclerViewAdapter(List<ModelData> users, Context context) {
this.users = users;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.layout_row, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder( ViewHolder holder, int position) {
ModelData user = users.get(position);
holder.nomeUser.setText(user.getName());
holder.userImage.setImageResource(user.getUserImage());
}
#Override
public int getItemCount() {
return users.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nomeUser;
private ImageView userImage;
public ViewHolder( View itemView) {
super(itemView);
nomeUser = itemView.findViewById(R.id.nomeText);
userImage = itemView.findViewById(R.id.imageView);
context = itemView.getContext();
}
}
ModelData.java
package com.example.aicopolilattico.splashscreen;
import java.security.PublicKey;
public class ModelData {
private String name;
private int userImage;
public ModelData() {}
public ModelData(String name, int userImage ) {
this.name = name;
this.userImage = userImage;
}
public String getName() {
return name;
}
public int getUserImage() {
return userImage;
}
ActivityMain.java
package com.example.aicopolilattico.splashscreen;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class ActivityMan extends AppCompatActivity {
private RecyclerView recycleView;
private List<ModelData> users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activityone);
recycleView = findViewById(R.id.recycleView);
users = new ArrayList<>();
users.add(new ModelData("Jack and Jones", R.drawable.jackcjones111));
users.add(new ModelData("Marlboro", R.drawable.marlb));
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recycleView.setLayoutManager(linearLayoutManager);
recycleView.setAdapter(new RecyclerViewAdapter(users, this));
recycleView.setHasFixedSize(true);
}
Guys is really important.
Thanks in advance to have patience and time to give me. :)
[ ! ! ! UPDATES ! ! ! ]
I've tried to write the code below, but when I click on the item, it pick up me on the first activity of the app. Advices? Thank a lot
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private List<ModelData> users;
private Context context;
public RecyclerViewAdapter(List<ModelData> users, Context context)
{
this.users = users;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder( ViewGroup parent, int viewType)
{
View v = LayoutInflater.from(context.getApplicationContext()).inflate(R.layout.layout_row, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder( ViewHolder holder, int position)
{
final ModelData user = users.get(position);
holder.nomeUser.setText(user.getName());
holder.userImage.setImageResource(user.getUserImage());
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context,Photo_Man.class);
context.startActivity(intent);
}
});
}
#Override
public int getItemCount()
{
return users.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView nomeUser;
private ImageView userImage;
public ViewHolder( View itemView)
{
super(itemView);
nomeUser = itemView.findViewById(R.id.nomeText);
userImage = itemView.findViewById(R.id.imageView);
context = itemView.getContext();
}
}
}
can u replace click listener like below code
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context, Photo_Man.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
}
});
The best and easiest way to achieve that is sending a listener of that event from the activity to the recyclerview.
Something like this...
Create an interface for listening click events:
public interface OnItemClickListener {
void onItemClick();
}
Modify the adapter to receive the listener:
private OnItemClickListener listener;
public RecyclerViewAdapter(List<ModelData> users, Context context, OnItemClickListener listener ) {
this.users = users;
this.context = context;
this.listener = listener;
}
Create listener from activity (From here you can open new activities):
OnItemClickListener listener = new OnItemClickListener() {
#Override public void onItemClick() {
Intent intent = new Intent(ActivityMain.this, NewActivity.class);
startActivity(intent);
}
};
Send that interface to the adapter:
recycleView.setAdapter(new RecyclerViewAdapter(users, this, listener));
Set this listener to the views you want to observe the event:
#Override
public void onBindViewHolder( ViewHolder holder, int position) {
ModelData user = users.get(position);
holder.nomeUser.setText(user.getName());
holder.userImage.setImageResource(user.getUserImage());
holder.userImage.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
listener.onItemClick();
}
});
}
First go to you recyclerview adapter's onBindViewHolder method.
Then simply add below code. here itemView is the particular one item of recyclerview
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// here you go for second activity using intent
Intent intent = new Intent(context, SecondActivity.class); // here you need context from constructor, SecondActivity is another activity
context.startActivity(intent); // this will call the SecondActivity intent
((Activity)context).finish(); // this is for just finish current activity (OPTIONAL, as per requirement)
}
});
if you want to goto activity
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent intent = new Intent(context,SomeActivity.class);
context.startActivity(intent);
}
});
if you want to goto fragment
holder.nomeUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
FragmentManager manager = ((Activity) context).getFragmentManager();
manager.beginTransaction().replace(R.id.transaction,get_posts).addToBackStack(null).commit();
}
});
I have a RecyclerView and each CardView contains a TextView and an ImageView. Whenever I click an item, I want to set the image visibility to VISIBLE and to set the previous clicked item image's visibility to INVISIBLE.
This is my Adapter class :
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.ViewHolder>{
private Context context;
private List<Category> lista;
private LayoutInflater layoutInflater;
private IncomeCategoryActivity activity;
private static final int CATEGORY_REQUEST=6;
private static final int ITEM_EDIT=1;
private static final int ITEM_DELETE=2;
private static final int EDIT_REQUEST=7;
private int current_pos=-1;
public CategoryAdapter(List<Category> lista, Context context, IncomeCategoryActivity activity) {
this.context = context;
this.lista = lista;
this.activity=activity;
layoutInflater=LayoutInflater.from(context);
}
#Override
public CategoryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=layoutInflater.inflate(R.layout.category_layout, parent, false);
ViewHolder viewHolder=new ViewHolder(view, activity);
return viewHolder;
}
#Override
public void onBindViewHolder(CategoryAdapter.ViewHolder holder, int position) {
holder.imageView.setImageURI(lista.get(position).getUri());
holder.textView.setText(lista.get(position).getCategory());
holder.position = position;
holder.category=lista.get(position);
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return lista.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener{
public ImageView imageView;
public TextView textView;
public ImageView imageViewCheck;
public int position;
public Category category;
public IncomeCategoryActivity activity;
public ViewHolder(View itemView, IncomeCategoryActivity activity) {
super(itemView);
this.activity=activity;
imageView=itemView.findViewById(R.id.customCategoryImageView);
textView=itemView.findViewById(R.id.customCategoryTextView);
imageViewCheck=itemView.findViewById(R.id.customCheckImageView);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
String aux=textView.getText().toString();
if(aux=="CATEGORIE NOUĂ"){
Intent intent=new Intent(context, CustomIncomeActivity.class);
activity.startActivityForResult(intent, CATEGORY_REQUEST);
}
else{
imageViewCheck.setVisibility(View.VISIBLE);
int pozitie_check=getLayoutPosition();
Intent intent=new Intent(context, AddIncomeActivity.class);
intent.putExtra("categorie_venit", aux);
intent.putExtra("position_check", pozitie_check);
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Selectează acțiunea");
MenuItem edit=menu.add(0, ITEM_EDIT, 0, "Modifică");
MenuItem delete=menu.add(0, ITEM_DELETE, 0, "Șterge");
edit.setOnMenuItemClickListener(this);
delete.setOnMenuItemClickListener(this);
}
#Override
public boolean onMenuItemClick(MenuItem item) {
int position=getLayoutPosition();
if (item.getGroupId() == 0) {
if(item.getItemId()==ITEM_EDIT){
Category category=lista.get(position);
Intent intent=new Intent(activity, CustomIncomeActivity.class);
intent.putExtra("edit_icon", category.getUri());
intent.putExtra("edit_category", category.getCategory());
intent.putExtra("list_position", position);
activity.startActivityForResult(intent, EDIT_REQUEST);
}
else if(item.getItemId()==ITEM_DELETE){
lista.remove(position);
notifyDataSetChanged();
}
}
return true;
}
At this moment, whenever I click an item, there are two images VISIBLE on the RecyclerView: the clicked item's image and the previous clicked item's image. I think I need to get the previous View by its position and to manually set the visibility to INVISIBLE.
recycleView.getChildCount() and recycleView_parent.getChildAt() only gives the Adapter items which is shows only screen .
that means if your list has 200 items and the only 5 items shows on screen so we can find only 5 item with the help of recycleView
i am using one simple trick to solve the issue.
You can define Hashmap which hold your holder objects
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
ArrayList<Model> dataList;
Context context;
HashMap<Integer,ViewHolder> holderlist;
public MyAdapter(ArrayList<Model> dataList, Context context) {
this.context = context;
this.dataList = dataList;
holderlist = new HashMap<>();
}
And after that to save the holder in Hashmap
public void onBindViewHolder(final ViewHolder holder, final int position) {
if(!holderlist.containsKey(position)){
holderlist.put(position,holder);
}
Create a method in Adapter.
public MyListAdapter.ViewHolder getViewByPosition(int position) {
return holderlist.get(position);
}
Call this method from your Activity or whenever you want.
for (int i = 0; i < datalList.size(); i++) {
MyAdapter.ViewHolder holder = ((MyAdapter)recycleView.getAdapter()).getViewByPosition(i);
View view = holder.itemView;
TextView tv = view.findViewById(R.id.tv);
}
I have created the demo you can refer it and implement for single selection
recyclerView.setAdapter(new RecyclerView.Adapter() {
int selected_position = -1;
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new RecyclerView.ViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.row_color_list,parent,false)) {
#Override
public String toString() {
return super.toString();
}
};
}
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
ImageView imageView = holder.itemView.findViewById(R.id.image);
if(selected_position == position){
imageView.setVisibility(View.VISIBLE);
}else {
imageView.setVisibility(View.GONE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selected_position != holder.getAdapterPosition()){
selected_position = holder.getAdapterPosition();
notifyDataSetChanged();
}
}
});
}
#Override
public int getItemCount() {
return 20;
}
});
You can do as following:
1) Declare a global variable:
private int selectedPos = -100; // Put any irrelevant number you want
2) Set selected position onClick() :
#Override
public void onClick(View v) {
selectedPos = getAdapterPosition();
}
3) Check selected postion and assign visibility inside onBindViewHolder():
#Override
public void onBindViewHolder(#NonNull final RecyclerView.ViewHolder holder, int position) {
if(position == selectedPos){
holder.imageViewCheck.setVisibility(View.VISIBLE);
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
}
Try this code..
add this code into adapter class for handling click event..
OnItemClick onItemClick;
public void setOnItemClick(OnItemClick onItemClick) {
this.onItemClick = onItemClick;
}
public interface OnItemClick {
void getPosition(String data); //pass any data to shared it.
}
after bind method..
#Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {
// below code handle click event on recycler view item.
final String str=mStringList.get(position); // here your boject
if(holder.category.isChecked()==true){
holder.imageViewCheck.setVisibility(View.VISIBLE);
current_pos=position;
} else {
holder.imageViewCheck.setVisibility(View.INVISIBLE);
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClick.getPosition(str); // pass your data.
}
});
}
after bind adapter into recycler view it means adapter not null then called below code..
adpater.setOnItemClick(new RecyclerViewAdpater.OnItemClick() {
#Override
public void getPosition(String data) {
// hear update your value for check into if condition.
data="sdfsdf";
adpater.notifyDataSetChanged();
}
});
and also read comments and also try to make custon class and access that object value and update after click it..
this code only how to handle click event into recycler view.
I have a recyclerview with an 30 images and on click of particular image i am opening a new activity which shows a different image.I have uploaded my images to a server and accessing the image from there. When my activity is opened on click ofrecyclerview` i am passing the position through intent so that i can know which image was clicked,then i am using switch case in my activity and load whatever image i want.I have written 30 cases of switch as i have 30 images.Is there any alternative to this.I don't want to use if and else if.
public class ModelLineUpAdapter extends RecyclerView.Adapter<ModelLineUpAdapter.MyViewHolder> {
private Context context;
private List<Bikers> bikersList;
public ModelLineUpAdapter(List<Bikers> bikersList,Context context) {
this.bikersList=bikersList;
this.context = context;
}
public static class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public ImageView bikesImageView;
public TextView nameTextView, priceTextView;
private Button brocheurebutton;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
bikesImageView = itemView.findViewById(R.id.bikelistitemImageview);
nameTextView = itemView.findViewById(R.id.bikelistitemname);
priceTextView = itemView.findViewById(R.id.bikelistitemprice);
brocheurebutton = itemView.findViewById(R.id.bikelistitembutton);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ModelLineUpInnerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("position",getAdapterPosition());
context.startActivity(intent);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.bikelistitem, null);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Bikers bikers = bikersList.get(position);
holder.nameTextView.setText(bikers.getBikename());
holder.priceTextView.setText(bikers.getBikeprice());
Glide.with(context).load(bikers.getBikeImageUrl()).into(holder.bikesImageView);
}
#Override
public int getItemCount() {
//Log.i(TAG, "getItemCount: "+bikersList.size());
return bikersList == null ? 0 : bikersList.size();
}
}
just pass image url with intent and recieve in your ModelLineUpInnerActivity
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ModelLineUpInnerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("position",getAdapterPosition());
intent.putExtra("IMG",bikersList.get(getAdapterPosition()).getBikeImageUrl());
context.startActivity(intent);
}
I tried to set an Onclick event for my cardView. As you can see, I created that event inside the OnBindViewHolder but the problem is that the startActivity method didn't identify.What do you think i should do? Thank you in advance and sorry for my English :)
public class AdapterVRList extends RecyclerView.Adapter<AdapterVRList.CourseViewHolder> {
private Context context;
private List<DObjectVrList> DObjectVrListList;
public AdapterVRList(Context context, List<DObjectVrList> DObjectVrListList){
this.context = context;
this.DObjectVrListList = DObjectVrListList;
}
public AdapterVRList(Context context){
}
#Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.card_vr,parent,false);
return new CourseViewHolder(view);
}
#Override
public void onBindViewHolder(CourseViewHolder holder, int position) {
DObjectVrList DObjectVrList = DObjectVrListList.get(position);
holder.CourseText.setText(DObjectVrList.getTitleCourse());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CourseInnerPage course = new CourseInnerPage(getItemCount());
Intent intent = new Intent(context,CourseInnerPage.class);
startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return 8;
}
public class CourseViewHolder extends RecyclerView.ViewHolder{
private TextView CourseText;
public CourseViewHolder(View itemView) {
super(itemView);
CourseText = (TextView) itemView.findViewById(R.id.course_text);
}
}
}
The error is: Cannot resolve the startActivity method
Because your adapter or its superclasses do not have the method startActivity().
Use context.startActivity();
use context.startActivity(intent)
I've got a RecyclerView which is loading the content of my String Arrays which works fine, however I want to open a new Activity depending on which view they have pressed.
What I have done:
public class WinnersListAdapter extends RecyclerView.Adapter<WinnersListAdapter.WinnersCardViewHolder>
{
Context context;
LayoutInflater inflater;
List<ListLottery> lotteryList;
public WinnersListAdapter(List<ListLottery> loteries,Context context){
this.context = context;
this.lotteryList = loteries;
inflater = LayoutInflater.from(context);
}
#Override
public WinnersListAdapter.WinnersCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = inflater.inflate(R.layout.prevlotterycards_layout,parent,false);
// Toast.makeText(context,"Hi",Toast.LENGTH_SHORT).show();
WinnersListAdapter.WinnersCardViewHolder viewHolder = new WinnersListAdapter.WinnersCardViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(WinnersListAdapter.WinnersCardViewHolder holder, int position) {
final ListLottery lottery = lotteryList.get(position);
holder.lottery_date.setText(lottery.getLotteryDate());
holder.lottery_date.setTag(holder);
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,"clicked--"+lottery.getLotteryId(),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,WinnerActivity.class);
intent.putExtra("lotteryId",lottery.getLotteryId());
context.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return lotteryList.size();
}
class WinnersCardViewHolder extends RecyclerView.ViewHolder {
TextView lottery_date;
CardView card_lotteryList;
public WinnersCardViewHolder(View itemView) {
super(itemView);
lottery_date = (TextView) itemView.findViewById(R.id.l_lottery_date);
card_lotteryList = (CardView) itemView.findViewById(R.id.card_lotteryList);
}
}
}
I have read many articles to resolve it and did stuff according that but could not find any solution.
Actually, I can not answer your question because you didn't post your logcat but there are few things you can check :
1 - Check that your activity already declared in AndroidManifest.xml
2 - Check you context is the context of Activity or applicationContext ?
If is't not the context of Activity so you need to add flag
Intent i = new Intent(this, WinnerActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);