Recyclerview items don't answer for first click - android

I'm having a problem with assigning onclicklistener to recyclerview items.
When I click the item, first click is ignored and listener doesn't run.
I mean, I have to click once, and then again to run the listener.
Once it runs, listener works well.
here is my code.
public class BoardFragment extends Fragment {
//recycler view ingredient
private RecyclerView recyclerView_board;
public static board_adapter mboard_adapter;
public static ArrayList<board_item> board_itemList;
private RecyclerView.LayoutManager board_LayoutManager;
//recycler view ingredient end
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(fragment_board, container, false);
//recycler view setting
recyclerView_board = (RecyclerView) v.findViewById(R.id.board_recycler);
board_itemList = new ArrayList<board_item>();
board_LayoutManager = new LinearLayoutManager(getActivity());
mboard_adapter = new board_adapter(board_itemList);
recyclerView_board.setAdapter(mboard_adapter);
recyclerView_board.setLayoutManager(board_LayoutManager);
recyclerView_board.setItemAnimator(new DefaultItemAnimator());
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView_board.getContext(), DividerItemDecoration.VERTICAL);
recyclerView_board.addItemDecoration(dividerItemDecoration);
board_item item = new board_item();
item.setName("Hello");
board_itemList.add(item);
mboard_adapter.notifyDataSetChanged();
//recycler view setting end
return v;
}
public static class board_item {
private String name;
private CheckBox button;
private int state = 0;
public String getName() {
return this.name;
}
public CheckBox getButton() {
return this.button;
}
public int getState() {
return this.state;
}
public void setName(String name) {
this.name = name;
}
public void setButton(CheckBox button) {
this.button = button;
}
public void setState(int state) {
this.state = state;
}
}
public class board_adapter extends RecyclerView.Adapter<board_adapter.ViewHolder> {
private ArrayList<board_item> temp_board_array;
public board_adapter(ArrayList<board_item> board_itemList) {
temp_board_array = board_itemList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_board, parent, false);
view.setOnClickListener(new board_onclick_listener());
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
final int itemposition = position;
holder.board_name_text.setText(temp_board_array.get(position).getName());
class board_button_onclick_listener implements View.OnClickListener {
#Override
public void onClick(final View view) {
board_item item = board_itemList.get(itemposition);
Toast.makeText(view.getContext(), "button clicked", Toast.LENGTH_LONG).show();
if(item.getState() == 0){
}
else {
}
}
}
holder.board_favorite_button.setOnClickListener(new board_button_onclick_listener());
}
#Override
public int getItemCount() {
return temp_board_array.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView board_name_text;
public CheckBox board_favorite_button;
public ViewHolder(View itemView) {
super(itemView);
board_name_text = (TextView) itemView.findViewById(R.id.board_name);
board_favorite_button = (CheckBox) itemView.findViewById(R.id.board_favorite_button);
}
}
//각 아이템에 적용될 리스너
class board_onclick_listener implements View.OnClickListener {
#Override
public void onClick(final View view) {
int itemposition = recyclerView_board.getChildLayoutPosition(view);
board_item item = board_itemList.get(itemposition);
Toast.makeText(view.getContext(), item.getName() + " selected", Toast.LENGTH_LONG).show();
Intent intent = new Intent(view.getContext(), CardActivity.class);
view.getContext().startActivity(intent);
}
}
}
}

Related

ItemView.setOnCLickListiner is Being Ignored and does not get clicked when it is clicked

please can anyone help me fix this my itemview is not being clicked wen i click it in my fragment after implementing my onItemClickListener interface in my adapter, i also called the adapter in my fragment but if i run the app and i click d cardview nothing happens and am using list adapter which extends recyclerView. please if anyone can help me i will b grateful
my adapter
public class Apiary_Adapter extends ListAdapter<RecordModel,Apiary_Adapter.ApiaryHolder> {
Apiaries apiaries;
Context context;
RecordOnClickListener listener;
public RecordViewModel record_View_model = Apiaries.record_View_model;
public Apiary_Adapter(Apiaries apiaries, Context context ) {
super(DIFF_CALLBACK);
this.apiaries = apiaries;
this.context = context;
}
private static final DiffUtil.ItemCallback<RecordModel> DIFF_CALLBACK = new DiffUtil.ItemCallback<RecordModel>() {
#Override
public boolean areItemsTheSame(#NonNull RecordModel oldItem, #NonNull RecordModel newItem) {
return oldItem.getId() == newItem.getId();
}
#Override
public boolean areContentsTheSame(#NonNull RecordModel oldItem, #NonNull RecordModel newItem) {
return oldItem.getAddress().equals(newItem.getAddress())&&oldItem.getApiaryNo().equals(newItem.getApiaryNo())
&&oldItem.getTown().equals(newItem.getTown())&&oldItem.getApiaryLongitude().equals(newItem.getApiaryLongitude())
&&oldItem.getApiaryLatitude().equals(newItem.getApiaryLatitude())&&oldItem.getDateOfHarvest().equals(newItem.getDateOfHarvest())
&&oldItem.getDateOfColonisation().equals(newItem.getDateOfColonisation())&&oldItem.getNoOfWaxHarvested().equals(newItem.getNoOfWaxHarvested())
&&oldItem.getQuantityOfHoneyHarvested().equals(newItem.getQuantityOfHoneyHarvested())&&oldItem.getNoOfPropolis().equals(newItem.getNoOfPropolis())
&&oldItem.getNoOfCombs().equals(newItem.getNoOfCombs())&&oldItem.getHiveNo().equals(newItem.getHiveNo())
&&oldItem.getHiveLongitude().equals(newItem.getHiveLongitude())&&oldItem.getHiveLatitude().equals(newItem.getHiveLatitude())
&&oldItem.getTime().equals(newItem.getTime())&&oldItem.getDate().equals(newItem.getDate());
}
};
public class ApiaryHolder extends RecyclerView.ViewHolder {
private TextView address;
private TextView apiary;
private TextView town;
private TextView LocationLatitude;
private TextView LocationLongitude;
private TextView HiveLatitude;
private TextView HiveLongitude;
private TextView date;
private TextView time;
private TextView hiveNo;
private TextView noOfComb;
private TextView dateOfHarvest;
private TextView dateOfColonisation;
private TextView waxHarvested;
private TextView quantityOfhoney;
private TextView noOfPropolis;
private CheckBox checkBox;
CardView cardView;
Apiaries apiaries;
public ApiaryHolder(#NonNull final View itemView, final Apiaries apiaries) {
super(itemView);
address = itemView.findViewById(R.id.customAddress);
apiary = itemView.findViewById(R.id.customApiaryNo);
town = itemView.findViewById(R.id.customTown);
LocationLongitude = itemView.findViewById(R.id.customLongitude);
LocationLatitude = itemView.findViewById(R.id.customLatitude);
checkBox = itemView.findViewById(R.id.customCheckbox);
hiveNo = itemView.findViewById(R.id.customHiveNo);
noOfComb = itemView.findViewById(R.id.customCombNo);
dateOfHarvest = itemView.findViewById(R.id.customDateOfHarvest);
dateOfColonisation = itemView.findViewById(R.id.customDateOfColonisation);
waxHarvested = itemView.findViewById(R.id.customNoOfWaxHarveted);
quantityOfhoney = itemView.findViewById(R.id.customQuantityOfHoney);
noOfPropolis = itemView.findViewById(R.id.customNoOfPropolis);
HiveLatitude = itemView.findViewById(R.id.customHiveLatitude);
HiveLongitude = itemView.findViewById(R.id.customHiveLongitude);
date = itemView.findViewById(R.id.customDate);
time = itemView.findViewById(R.id.customTime);
cardView = itemView.findViewById(R.id.Cardview);
this.apiaries = apiaries;
mainActivity = new MainActivity();
cardView.setOnLongClickListener(apiaries);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int Position = getAdapterPosition();
if (listener != null && Position != RecyclerView.NO_POSITION){
listener.OnItemClick(getItem(Position));
Toast.makeText(context, "Hello9", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
}
}
});
}
#NonNull
#Override
public ApiaryHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customlayout, parent, false);
final ApiaryHolder apiaryHolder= new ApiaryHolder(itemView, apiaries);
return apiaryHolder;
}
#Override
public void onBindViewHolder(#NonNull ApiaryHolder holder, final int position) {
RecordModel currentRecord = getItem(position);
holder.address.setText(currentRecord.getAddress());
holder.apiary.setText(currentRecord.getApiaryNo());
holder.town.setText(currentRecord.getTown());
holder.LocationLatitude.setText(currentRecord.getApiaryLatitude());
holder.LocationLongitude.setText(currentRecord.getApiaryLongitude());
holder.hiveNo.setText(currentRecord.getHiveNo());
holder.noOfComb.setText(currentRecord.getNoOfCombs());
holder.dateOfHarvest.setText(currentRecord.getDateOfHarvest());
holder.dateOfColonisation.setText(currentRecord.getDateOfColonisation());
holder.waxHarvested.setText(currentRecord.getNoOfWaxHarvested());
holder.quantityOfhoney.setText(currentRecord.getQuantityOfHoneyHarvested());
holder.noOfPropolis.setText(currentRecord.getNoOfPropolis());
holder.HiveLatitude.setText(currentRecord.getHiveLatitude());
holder.HiveLongitude.setText(currentRecord.getHiveLongitude());
holder.date.setText(currentRecord.getDate());
holder.time.setText(currentRecord.getTime());
}
public interface RecordOnClickListener{
void OnItemClick(RecordModel recordModel);
}
public void setOnItemClickListener(RecordOnClickListener listener){
this.listener = listener;
}
my fragment
public class Apiaries extends Fragment implements View.OnLongClickListener {
public static boolean is_in_contextualMode = false;
public static RecordViewModel record_View_model;
Apiary_Adapter apiary_adapter;
public static int counter = 0;
public static ArrayList<RecordModel> selectionList =new ArrayList<>();
private RecyclerView recyclerView;
public static SearchView searchView;
public static final int ADD_RECORD_REQUEST = 1;
public static final int EDIT_RECORD_REQUEST = 2;
com.github.clans.fab.FloatingActionButton floatingActionButton;
FirebaseAuth firebaseAuth;
DatabaseReference reference;
public static MainActivity mainActivity;
private Menu menu;
ArrayList<RecordModel> list = new ArrayList<>();
public Apiaries() {
// Required empty public constructor
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_apiaries, container, false);
floatingActionButton = (FloatingActionButton) view.findViewById(R.id.fab2);
Apiaries apiaries = new Apiaries();
apiary_adapter = new Apiary_Adapter(apiaries, getActivity());
firebaseAuth = FirebaseAuth.getInstance();
String currentUserId = firebaseAuth.getCurrentUser().getUid();
reference = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserId);
recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(apiary_adapter);
recyclerView.setHasFixedSize(true);
return view;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainActivity = new MainActivity();
record_View_model = new ViewModelProvider(getActivity()).get(RecordViewModel.class);
record_View_model.getAllRecord().observe(getActivity(), new Observer<List<RecordModel>>() {
#Override
public void onChanged(#Nullable List<RecordModel> recordModels) {
apiary_adapter.submitList(recordModels);
}
});
apiary_adapter.setOnItemClickListener(new Apiary_Adapter.RecordOnClickListener() {
#Override
public void OnItemClick(RecordModel recordModel) {
Intent intent = new Intent(getContext(), EditApiaryAddActivity.class);
intent .putExtra(EditApiaryAddActivity.EXTRA_ID, recordModel.getId());
intent .putExtra(EditApiaryAddActivity.EXTRA_ADDRESS, recordModel.getAddress());
intent .putExtra(EditApiaryAddActivity.EXTRA_APIARYNAME, recordModel.getApiaryNo());
intent .putExtra(EditApiaryAddActivity.EXTRA_TOWN, recordModel.getTown());
intent .putExtra(EditApiaryAddActivity.EXTRA_LOCATION_LATITUDE, recordModel.getApiaryLatitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_LOCATION_LONGITUDE, recordModel.getApiaryLongitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_HIVE_LATITUDE, recordModel.getHiveLatitude());
intent .putExtra(EditApiaryAddActivity.EXTRA_HIVE_LONGITUDE, recordModel.getHiveLongitude());
intent.putExtra(EditApiaryAddActivity.EXTRA_HIVENO, recordModel.getHiveNo());
intent.putExtra(EditApiaryAddActivity.EXTRA_NOOFCOMBS, recordModel.getNoOfCombs());
intent.putExtra(EditApiaryAddActivity.EXTRA_DATEOFHARVEST, recordModel.getNoOfWaxHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_DATEOFCOLONISATION, recordModel.getDateOfColonisation());
intent.putExtra(EditApiaryAddActivity.EXTRA_WAXHARVESTED, recordModel.getNoOfWaxHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_QUANTITYOFHONEY, recordModel.getQuantityOfHoneyHarvested());
intent.putExtra(EditApiaryAddActivity.EXTRA_NOOFPROPOLIS, recordModel.getNoOfPropolis());
startActivityForResult(intent,EDIT_RECORD_REQUEST);
Apiaries.is_in_contextualMode = false;
mainActivity.clearActionMode();
}
});
}
#Override
public boolean onLongClick(View v) {
MainActivity.toolbar.getMenu().clear();
MainActivity.toolbar.inflateMenu(R.menu.menu_record);
MainActivity.textView1.setVisibility(View.GONE);
MainActivity.itemCountTextView.setVisibility(View.VISIBLE);
MainActivity.edit.setVisibility(View.VISIBLE);
is_in_contextualMode = true;
return true;
}
You should handle Clicks in the onCreateViewHolder method
public ApiaryHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.customlayout, parent, false);
final ApiaryHolder apiaryHolder= new ApiaryHolder(itemView, apiaries);
ApiaryHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle the clicks here
}
}
});
return apiaryHolder;
}
You have implemented onLongClickListener Instead of onClickListener
Add the onClickListener Inside on bindviewholder Like holder.itemView.setOnClickLstener

How to get onclick item in an android recyclerview and send its attributes to a new activity?

I'm developing an android app for online order. User needs to click on an food item in recyclerView and I'm trying to send the food ID to the AddOrderActivity. How can I get the FId and pass it to the new activity?
CustomerHomeFragment.java
public class CustomerHomeFragment extends Fragment {
private RecyclerView recyclerView;
private FoodsAdapter adapter;
private List<Food> foodList;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home_customer, container, false);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
Call<FoodsResponse> call = RetrofitClient.getInstance().getApi().getFoods();
call.enqueue(new Callback<FoodsResponse>() {
#Override
public void onResponse(Call<FoodsResponse> call, Response<FoodsResponse> response) {
foodList = response.body().getFoods();
adapter = new FoodsAdapter(getActivity(), foodList);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<FoodsResponse> call, Throwable t) {
}
});
}
}
public class FoodsAdapter extends RecyclerView.Adapter implements View.OnClickListener{
private Context mCtx;
private List<Food> foodList;
public FoodsAdapter(Context mCtx, List<Food> foodList) {
this.mCtx = mCtx;
this.foodList = foodList;
}
#NonNull
#Override
public FoodsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mCtx).inflate(R.layout.recyclerview_foods, parent, false);
return new FoodsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull FoodsViewHolder holder, int position) {
Food food = foodList.get(position);
holder.textViewFName.setText(food.getFName());
holder.textViewUnitPrice.setText(String.format("%d", food.getUnitPrice()));
holder.textViewAvailCount.setText(String.format("%d", food.getAvailCount()));
}
#Override
public int getItemCount() {
return foodList.size();
}
//////////////
#Override
public void onClick(View view) {
Intent intent = new Intent(this.mCtx, AddOrderActivity.class);
this.mCtx.startActivity(intent);
}
/////////////////
class FoodsViewHolder extends RecyclerView.ViewHolder {
TextView textViewFName, textViewUnitPrice, textViewAvailCount;
public FoodsViewHolder(View itemView) {
super(itemView);
textViewFName = itemView.findViewById(R.id.textViewFName);
textViewUnitPrice = itemView.findViewById(R.id.textViewUnitPrice);
textViewAvailCount = itemView.findViewById(R.id.textViewAvailCount);
}
}
}
public class Food {
private int fid, unitprice, availcount;
private String fname;
public Food(int fid, String fname, int unitprice, int availcount) {
this.fid = fid;
this.fname = fname;
this.unitprice = unitprice;
this.availcount = availcount;
}
public int getFId() {
return fid;
}
public String getFName() {
return fname;
}
public int getUnitPrice() {
return unitprice;
}
public int getAvailCount() {
return availcount;
}
}
in the your adapter class inside the onBindViewHolder function add this code
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(context,NoteActivity.class);
intent.putExtra("note_id", currentNote.getNoteId());
intent.putExtra("note_name",currentNote.getNoteName());
intent.putExtra("note_teacher",currentNote.getNoteTeacher());
intent.putExtra("note_university",currentNote.getNoteUniversity());
intent.putExtra("note_image",currentNote.getNoteImage());
intent.putExtra("note_is_downloaded", currentNote.getIsDownloaded());
intent.putExtra("note_storage_path", currentNote.getStoragePath());
intent.putExtra("note_download_link", currentNote.getNoteDownloadLink());
context.startActivity(intent);
}
});

Handle button click inside row in recyclerView

I would like to know how to handle position of the row if the adapter is changed - for example if I write something to SearchView - adapter has changed and position is different. I have done this (below), but it shows the item before changed position.
My issue is with Recycler view item click.
Could you help me with that?
Adapter
public class ContactsRecyclerAdapter extends RecyclerView.Adapter<ContactsRecyclerAdapter.BindingHolder> {
private static OnItemClickListener listener;
public interface OnItemClickListener {
void onItemClick(View itemView, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
private List<Contact> mContacts;
private List<Contact> mContactsFiltered;
SearchViewFilter filter;
Context mContext;
public ContactsRecyclerAdapter(Context context, List<Contact> contact) {
this.mContext = context;
this.mContacts = contact;
this.mContactsFiltered = contact;
filter = new SearchViewFilter(mContacts, this);
}
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null)
listener.onItemClick(itemView, getLayoutPosition());
}
});
}
public ViewDataBinding getBinding() {
return binding;
}
}
#Override
public BindingHolder onCreateViewHolder(ViewGroup parent, int type) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item_contact, parent, false);
BindingHolder holder = new BindingHolder(view);
return holder;
}
#Override
public void onBindViewHolder(BindingHolder holder, int position) {
final Contact contact = mContactsFiltered.get(position);
holder.getBinding().setVariable(BR.contact, contact);
holder.getBinding().executePendingBindings();
}
Fragment
public class ContactListFragment extends Fragment implements View.OnClickListener {
FloatingActionButton fabButton;
SearchView searchView;
RecyclerView recyclerView;
String name, number, email;
private List<Contact> mContact = new ArrayList<>();
private ContactsRecyclerAdapter mAdapter;
public static ContactListFragment newInstance() {
Bundle args = new Bundle();
ContactListFragment fragment = new ContactListFragment();
fragment.setArguments(args);
return fragment;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_contact_list, container, false);
searchView = (SearchView) view.findViewById(R.id.search_view);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
mContact = SugarRecord.listAll(Contact.class);
mAdapter = new ContactsRecyclerAdapter(getActivity(), mContact);
recyclerView.setAdapter(mAdapter);
//item click
mAdapter.setOnItemClickListener(new ContactsRecyclerAdapter.OnItemClickListener() {
#Override
public void onItemClick(View itemView, int position) {
Contact contact = SugarRecord.findById(Contact.class, (long) position + 1);
name = contact.getName();
number = contact.getNumber();
email = contact.getEmail();
showAlertDialog();
}
});
searchFilter();
return view;
}
public void sortList() {
if(mContact.size() > 0) {
if (!isSort) {
Collections.sort(mContact, new Comparator<Contact>() {
#Override
public int compare(Contact contact1, Contact contact2) {
return contact1.getName().compareToIgnoreCase(contact2.getName());
}
});
}
else {
Collections.reverse(mContact);
isSort = false;
}
}
mAdapter.notifyDataSetChanged();
Click listener does not work with a RecyclerView. use OnItemTouchListener()
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
#Override public void onLongItemClick(View view, int position) {
// do whatever
}
})
);
you have to overide onclick in BindingHolder class. Inside onclick method invoke a callback method of object passed via constructor etc
public static class BindingHolder extends RecyclerView.ViewHolder {
private ViewDataBinding binding;
public BindingHolder(final View rowView) {
super(rowView);
binding = DataBindingUtil.bind(rowView);
public void onClick(View view) {
//call a callback method here
}
}
public ViewDataBinding getBinding() {
return binding;
}
}

Recycler View + Stars instead of Checkboxes: keeping state while scrolling

I'm having the usual problem with a list + a RecyclerView: when I change the resource file of an item (aka: selected/unselected star icon) and then scroll, other items of the list are keeping the same selected/unselected state for their own star. Plus, when I select an item and then go back, I'm missing the selected/unselected state.
The fullStar and the emptyStar are simple Android Vector images.
Here it is my ListFragment:
public class PetrolStationListFragment extends Fragment {
private RecyclerView mPetrolStationRecyclerView;
private PetrolStationAdapter mAdapter;
private int itemPosition;
public static boolean toBeCreated;
private static final String ARG_POSITION = "position";
// Design pattern to instantiate a new fragment.
public static PetrolStationListFragment newInstance(int position) {
PetrolStationListFragment fragment = new PetrolStationListFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_petrol_station_list, container, false);
mPetrolStationRecyclerView = (RecyclerView) view.findViewById(R.id.petrol_recycler_view);
mPetrolStationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
PetrolStationDAO petrolStationDAO = PetrolStationDAO.get(getActivity());
List<PetrolStation> petrolStations = petrolStationDAO.getPetrolStations();
if (mAdapter == null || toBeCreated) {
mAdapter = new PetrolStationAdapter(petrolStations);
mPetrolStationRecyclerView.setAdapter(mAdapter);
toBeCreated = false;
} else {
mAdapter.notifyItemChanged(itemPosition);
}
}
private class PetrolStationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PetrolStation mPetrolStation;
private TextView mNameTextView;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private AppCompatImageView mStar;
private boolean mFavourite;
public PetrolStationHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.list_item_station_name_text_view);
mAddressTextView = (TextView) itemView.findViewById(R.id.list_item_station_address_text_view);
mDistanceTextView = (TextView) itemView.findViewById(R.id.list_item_station_distance_text_view);
mStar = (AppCompatImageView) itemView.findViewById(R.id.list_item_station_star_image_view);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
}
public void bindPetrolStation(PetrolStation petrolStation) {
mPetrolStation = petrolStation;
mNameTextView.setText(mPetrolStation.getName());
mAddressTextView.setText("Via Verdi, 19/A");
mDistanceTextView.setText("300 meters");
mFavourite = mPetrolStation.isFavourite(mStar);
Log.d("FAVOURITE", "mFavourite: " + mFavourite);
//setStarByBoolean();
mStar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setStarByTag();
}
});
}
#Override
public void onClick(View v) {
//itemPosition = mPetrolStationRecyclerView.getChildAdapterPosition(v);
Intent intent = PetrolStationPagerActivity.newIntent(getActivity(), mPetrolStation.getId());
startActivity(intent);
}
public void setStarByBoolean() {
if (!mFavourite) {
mStar.setImageResource(R.drawable.ic_star_border_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
} else {
mStar.setImageResource(R.drawable.ic_star_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "fullStar");
}
}
public void setStarByTag() {
if (mStar.getTag(R.id.list_item_station_star_image_view).equals("emptyStar")) {
mStar.setImageResource(R.drawable.ic_star_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "fullStar");
} else {
mStar.setImageResource(R.drawable.ic_star_border_orange);
mStar.setTag(R.id.list_item_station_star_image_view, "emptyStar");
}
}
}
private class PetrolStationAdapter extends RecyclerView.Adapter<PetrolStationHolder> {
private List<PetrolStation> mPetrolStations;
public PetrolStationAdapter(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
}
#Override
public PetrolStationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_petrol_station, parent, false);
return new PetrolStationHolder(view);
}
#Override
public void onBindViewHolder(PetrolStationHolder holder, int position) {
PetrolStation petrolStation = mPetrolStations.get(position);
Log.d("POSITION", "position: " + position);
holder.bindPetrolStation(petrolStation);
}
#Override
public int getItemCount() {
return mPetrolStations.size();
}
}
}
And here a the getter and the setter for the PetrolStation Model class:
public boolean isFavourite(AppCompatImageView star) {
if (star.getTag(R.id.list_item_station_star_image_view).equals("emptyStar")) {
mFavourite = false;
} else {
mFavourite = true;
}
return mFavourite;
}
public void setFavourite(boolean favourite) {
this.mFavourite = favourite;
}
Any hint about how to fix this issue? I'm finding difficult to apply the CheckBoxes examples I've found to my own case.

Send data from CardView in RecyclerView to new fragment?

So I have a CardView in a RecyclerView which has some data inside it. I would like to click on a specific card and launch a new fragment that displays specific data from the data in the CardView (more details about the data in the CardView). Here is the relevant code.
I don't have the most experience in programming and Android in general, any help would be appreciated!
DetailsFragment: `
public class DetailsFragment extends Fragment {
private CardView cardView;
private RecyclerView rv;
private List<Detail> detailList = new ArrayList<>();
public DetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details, container, false);
Context context = getActivity();
cardView = (CardView) rootView.findViewById(R.id.cv);
rv = (RecyclerView) rootView.findViewById(R.id.rv);
final LinearLayoutManager llm = new LinearLayoutManager(context);
rv.setLayoutManager(llm);
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
initializeData();
initializeAdapter();
return rootView;
}
private void initializeData() {
detailList = new ArrayList<>();
// not sure here
detailList.add(new Detail(" "));
}
private void initializeAdapter(){
RVDetailAdapter adapter = new RVDetailAdapter(detailList);
rv.setAdapter(adapter);
}
}
RVNewsAdapater:
public class RVNewsAdapter extends RecyclerView.Adapter<RVNewsAdapter.NewsViewHolder> {
public static final String KEY_LINK ="link";
public static class NewsViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private static final String TAG = "Hello";
CardView cv;
TextView date;
TextView link;
TextView title;
TextView today;
public NewsViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
date = (TextView) itemView.findViewById(R.id.date);
link = (TextView) itemView.findViewById(R.id.link);
title = (TextView) itemView.findViewById(R.id.heading);
today = (TextView) itemView.findViewById(R.id.today);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent intent = null;
for(int postion = 0; postion<42; postion++) {
intent = new Intent(context, Details.class);
}
context.startActivity(intent);
}
}
List<News> news;
RVNewsAdapter(List<News> news) {
this.news = news;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVNewsAdapter.NewsViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
NewsViewHolder nvh = new NewsViewHolder(v);
return nvh;
}
#Override
public void onBindViewHolder(NewsViewHolder newsViewHolder, int i) {
newsViewHolder.date.setText(news.get(i).date);
newsViewHolder.link.setText(news.get(i).link);
newsViewHolder.title.setText(news.get(i).title);
newsViewHolder.today.setText(news.get(i).today);
}
#Override
public int getItemCount() {
if (news != null) {
return news.size();
}
return 0;
}
}
RVDetailAdapter:
public class RVDetailAdapter extends RecyclerView.Adapter<RVDetailAdapter.DetailViewHolder> {
public static class DetailViewHolder extends RecyclerView.ViewHolder {
TextView link;
public DetailViewHolder(View itemView) {
super(itemView);
link = (TextView) itemView.findViewById(R.id.link);
}
}
List<Detail> detail;
RVDetailAdapter(List<Detail> detail) {
this.detail = detail;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public RVDetailAdapter.DetailViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemnewsfeed, viewGroup, false);
DetailViewHolder dvh = new DetailViewHolder(v);
return dvh;
}
#Override
public void onBindViewHolder(DetailViewHolder detailViewHolder, int i) {
detailViewHolder.link.setText(detail.get(i).link);
}
#Override
public int getItemCount() {
if (detail != null) {
return detail.size();
}
return 0;
}
}
Not sure if you're still looking for an answer, but I just saw the post and thought I'd give you one option.
When I'm using a RecyclerView (doesn't matter if it's using the CardView or not, it's the same for any list item), I create a a click listener for the view item in the Adapter. When the user clicks the item/cardview, I dispatch an item click event. It's your choice on how you respond - you can use a standard callback interface (and pass in your listener when you create the adapter) or use something like EventBus.
Here's an example of the code you would add to your adapter class:
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(itemLayout, parent, false);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemClick(view);
}
});
return new ViewHolder(view);
}
private void itemClick(View view) {
//Handle item event here
//EventBus.getDefault().post(new ItemSelectedEvent(/*send apprpopriate data*/));
}

Categories

Resources