How to autoselect 1st item from RecyclerView? - android

I have a recyclerView in my app that contain a list of Menu and when i press one of them if will change items in another recyclerView but when i open my activity noone of recyclerView where there are the menu's are selected.
So the question is how can i open the activity and find the 1st item of the recyclerView selected?
I was trying to simulate an click by Handler but it was making my app slower.
Here is the code from my Adapter :
public class RecyclerViewMenu extends RecyclerView.Adapter<RecyclerViewMenu.MenuViewHolder> {
private ArrayList<MenuConstructor> menuConstructors;
private OnItemClickListener onItemClickListener;
private int selected_position = -1;
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
onItemClickListener = listener;
}
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.menucard,parent,false);
return new MenuViewHolder(v, onItemClickListener);
}
RecyclerViewMenu(ArrayList<MenuConstructor> menuList){
menuConstructors = menuList;
}
#Override
public void onBindViewHolder(#NonNull final MenuViewHolder holder, final int position) {
MenuConstructor currentItem = menuConstructors.get(position);
if (selected_position == position) {
holder.itemView.setBackgroundColor(Color.parseColor("#2e7d32"));
} else {
holder.itemView.setBackgroundColor(Color.parseColor(currentItem.getSfondoColor()));
}
holder.textView.setText(currentItem.getDesk());
holder.textView.setTextColor(Color.parseColor(currentItem.getFontColor()));
}
#Override
public int getItemCount() {
return menuConstructors.size();
}
public class MenuViewHolder extends RecyclerView.ViewHolder {
public TextView textView;
MenuViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
textView = itemView.findViewById(R.id.ButtonName);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
selected_position = position;
notifyDataSetChanged();
}
}
}
});
}
}
}
And here is a screenshot of my activity as you can see "CICCIO" is my first item of the recyclerView but it was selected manually.

Have you tried this in your activity:
recyclerView.findViewHolderForAdapterPosition(0).itemView.performClick()

The variable selected_position should be public in a Utils class and then you set selected_position = 0 in onCreate:
public class Utils {
public static final int selected_position = -1;
}
then you use it in onCreate Utils.selected_position = 0;
and in onBindViewHolder if (position == Utils.selected_position)
Of course you have to remove this line: private int selected_position = -1;

Hi you can use performClick() function..
if(positon == 0)
holder.itemView.performClick();

Related

Android Recycler View Adapter OnClickListener inside another Adapter

I have the following Adapter :
public class TeambuilderAdapter extends RecyclerView.Adapter<TeambuilderAdapter.ViewHolder> implements ItemTouchHelperAdapter {
private List<PokemonTeam> mData;
private LayoutInflater mInflater;
private ItemClickListener mClickListener;
private Context mContext;
private PokemonFavoritesAdapter pokemonFavoritesAdapter;
private GridLayoutManager gridLayoutManager;
// data is passed into the constructor
public TeambuilderAdapter(Context context, List<PokemonTeam> data) {
this.mInflater = LayoutInflater.from(context);
this.mData = data;
mContext = context;
setHasStableIds(true);
}
#Override
public long getItemId(int position) {
PokemonTeam pokemonTeam = mData.get(position);
return (pokemonTeam.getName()).hashCode();
}
// inflates the row layout from xml when needed
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_item_teambuilder, parent, false);
return new ViewHolder(view);
}
// binds the data to the TextView in each row
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
PokemonTeam pokemonTeam = mData.get(position);
gridLayoutManager = new GridLayoutManager(mContext, 6);
pokemonFavoritesAdapter = new PokemonFavoritesAdapter(mContext, pokemonTeam.getPokemonList());
holder.teamSpritesRecyclerView.setAdapter(pokemonFavoritesAdapter);
holder.teamSpritesRecyclerView.setLayoutManager(gridLayoutManager);
String pokemonTeamName = pokemonTeam.getName();
if (pokemonTeamName != null && !pokemonTeamName.isEmpty()) {
holder.teamTitleTextView.setText(pokemonTeam.getName());
}
}
// total number of rows
#Override
public int getItemCount() {
int size = 0;
if (Objects.nonNull(mData)) {
size = mData.size();
}
return size;
}
#Override
public void onItemMove(int fromPosition, int toPosition) {
if (fromPosition < toPosition) {
for (int i = fromPosition; i < toPosition; i++) {
Collections.swap(mData, i, i + 1);
}
} else {
for (int i = fromPosition; i > toPosition; i--) {
Collections.swap(mData, i, i - 1);
}
}
notifyItemMoved(fromPosition, toPosition);
((PokemonTeambuilderActivity) mContext).refreshTeamList();
}
#Override
public void onItemDismiss(int position) {
mData.remove(position);
notifyItemRemoved(position);
((PokemonTeambuilderActivity) mContext).refreshTeamList();
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView teamTitleTextView;
RecyclerView teamSpritesRecyclerView;
CardView pokemonTeambuilderContainer;
ViewHolder(View itemView) {
super(itemView);
teamTitleTextView = itemView.findViewById(R.id.pokemonTeambuilderTitleTextView);
teamSpritesRecyclerView = itemView.findViewById(R.id.pokemonTeambuilderSpritesLayout);
pokemonTeambuilderContainer = itemView.findViewById(R.id.pokemonTeambuilderContainer);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
// convenience method for getting data at click position
public PokemonTeam getItem(int id) {
return mData.get(id);
}
// allows clicks events to be caught
public void setClickListener(ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
}
In onBindViewHolder method I call another adapter inside this adapter which follows the same OnClickListener structure :
public class PokemonFavoritesAdapter extends RecyclerView.Adapter<PokemonFavoritesAdapter.ViewHolder> {
private Context mContext;
private List<Pokemon> favoritePokemon;
private LayoutInflater mInflater;
private PokemonFavoritesAdapter.ItemClickListener mClickListener;
public PokemonFavoritesAdapter(Context context, List<Pokemon> list) {
this.mInflater = LayoutInflater.from(context);
mContext = context;
favoritePokemon = list;
}
#NonNull
#Override
public PokemonFavoritesAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = mInflater.inflate(R.layout.list_item_pokemon_favorite, parent, false);
return new PokemonFavoritesAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull PokemonFavoritesAdapter.ViewHolder holder, int position) {
Pokemon pokemon = favoritePokemon.get(position);
String pokemonId = pokemon.get_id();
int dominantColor = PokemonUtils.getDominantColorFromPokemon(pokemonId, mContext);
int lighterDominantColor = PokemonUtils.lighterColor(dominantColor, GenericConstants.DARK_FACTOR);
int pokemonImageId = PokemonUtils.getPokemonSugimoriImageById(pokemonId, mContext);
holder.circularImageView.setBorderColor(dominantColor);
holder.circularImageView.setBorderWidth(4);
holder.circularImageView.setCircleColor(lighterDominantColor);
holder.circularImageView.setShadowRadius(6);
Picasso.get().load(pokemonImageId).fit().into(holder.circularImageView);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemCount() {
int size = 0;
if (Objects.nonNull(favoritePokemon) && !favoritePokemon.isEmpty()) {
size = favoritePokemon.size();
}
return size;
}
// convenience method for getting data at click position
public Pokemon getItem(int id) {
return favoritePokemon.get(id);
}
// allows clicks events to be caught
public void setClickListener(PokemonFavoritesAdapter.ItemClickListener itemClickListener) {
this.mClickListener = itemClickListener;
}
// parent activity will implement this method to respond to click events
public interface ItemClickListener {
void onItemClick(View view, int position);
}
// stores and recycles views as they are scrolled off screen
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircularImageView circularImageView;
ViewHolder(View view) {
super(view);
circularImageView = view.findViewById(R.id.civ_pokemon_favorite);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (mClickListener != null) {
mClickListener.onItemClick(view, getAdapterPosition());
}
}
}
}
However I have a problem , my activity can't listen the click events that happens inside my nested adapter :
public class PokemonTeambuilderActivity extends AppCompatActivity implements TeambuilderAdapter.ItemClickListener {
#Override
public void onItemClick(View view, int position) {
}
I don't know how to reach the events that happens within my PokemonFavoritesAdapter in my TeambuilderAdapter , I supose that I must implement the PokemonFavoritesAdapter.OnClickListener interface in my TeambuilderAdapter but I don't know how to do it . Any hint ?

Recyclerview occasionally becomes un-clickable in Android

I have this strange issue with a recycler view that is giving me a lot of headache. The rows in the recyclerView are clickable and in general things work. But once in a while they stop working and I no longer can click on a row on the recyclerView.
To produce this, I quickly toggle between two fragments (using a bottom navigation menu) one of which contains the recyclerView . After few times of doing this, the recyclerView stops responding. When I scroll the recyclerView up and down, the problem immediately fixes itself.
I was wondering if anyone can suggest where I should look to pinpoint the root cause.
Thanks a lot in advance
Here is my code for the recycleView:
public class KidItemAdapter extends RecyclerView.Adapter<KidItemAdapter.KidTaskViewHolder> {
private ArrayList<KidItem> mKidItems;
private OnItemClickListener mListener;
private int[] rainbow;
public interface OnItemClickListener {
void onItemClick(int position);
void onMenuClick(int position, View view);
}
public void setOnItemClickListener(KidItemAdapter.OnItemClickListener listener) {
mListener = listener;
}
public static class KidTaskViewHolder extends RecyclerView.ViewHolder {
TextView textViewTaskDescription;
TextView textViewTaskPoint;
ImageView imageViewTaskMenu;
CardView kidItemCardView;
public KidTaskViewHolder(View itemView, OnItemClickListener listener) {
super(itemView);
textViewTaskDescription = itemView.findViewById(R.id.task_description_view);
textViewTaskPoint = itemView.findViewById(R.id.task_point_view);
imageViewTaskMenu = itemView.findViewById(R.id.task_menu_image_view);
kidItemCardView = itemView.findViewById(R.id.kidItemCardView);
kidItemCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (listener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position);
}
}
}
});
imageViewTaskMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && listener != null) {
listener.onMenuClick(position, imageViewTaskMenu);
}
}
});
}
}
public KidItemAdapter(ArrayList<KidItem> kidItems, Activity activity) {
this.mKidItems = kidItems;
rainbow = activity.getResources().getIntArray(R.array.rainbow);
}
#NonNull
#Override
public KidTaskViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.kid_item, parent, false);
KidTaskViewHolder evh = new KidTaskViewHolder(v, mListener);
return evh;
}
#Override
public void onBindViewHolder(#NonNull KidTaskViewHolder holder, int position) {
KidItem currentKid = mKidItems.get(position);
holder.textViewTaskDescription.setText(currentKid.getDescription());
holder.textViewTaskPoint.setText(String.valueOf(currentKid.getPoints()));
holder.kidItemCardView.setCardBackgroundColor(rainbow[currentKid.getDescription().length()%rainbow.length]);
if (GlobalVars.appUser.isKidUser())
holder.imageViewTaskMenu.setVisibility(View.INVISIBLE);
}
#Override
public int getItemCount() {
return mKidItems.size();
}
}
Try replacing getAdapterPosition with getLayoutPosition.
In your KidTaskViewHolder class after extending RecyclerView.ViewHolder also implement View.OnClickListener like below-
public class KidTaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {...
Instead of using setOnClickListener for your cardview just try overriding onClick method
inside KidTaskViewHolder Class like below and let me know if it works-
public static class KidTaskViewHolder extends RecyclerView.ViewHolder {
TextView textViewTaskDescription;
TextView textViewTaskPoint;
ImageView imageViewTaskMenu;
//CardView kidItemCardView;
public KidTaskViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(this);
textViewTaskDescription = itemView.findViewById(R.id.task_description_view);
textViewTaskPoint = itemView.findViewById(R.id.task_point_view);
imageViewTaskMenu = itemView.findViewById(R.id.task_menu_image_view);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
//(Do anything here)
}
}
}

I want to make my buttons in recyclerView toggleable means when clicked on one other all should be dssleted

when i click on one button others should be deselected how to achieve this
I have seen other answers in stack but none solved my problem or i was not able to undrestand properly
public class LocationAreaAdapter extends RecyclerView.Adapter<LocationAreaAdapter.ViewHolder> {
private int mSelectedItem = -1;
private ArrayList<String> mNames = new ArrayList<>();
private Context mContext;
private ArrayList<Boolean> isChecked=new ArrayList<>();
private AdapterView.OnItemClickListener onItemClickListener;
public LocationAreaAdapter(Context context,ArrayList<String> mNames ){
this.mContext=context;
this.mNames=mNames;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.locatin_area_cardview, viewGroup, false);
return new ViewHolder(view,this);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int i) {
holder.name.setText(mNames.get(i));
holder.name.setChecked(i == mSelectedItem);
//what to do here
}
#Override
public int getItemCount() {
return mNames.size();
}
public void onItemHolderClick(ViewHolder holder) {
if (onItemClickListener != null)
onItemClickListener.onItemClick(null, holder.itemView, holder.getAdapterPosition(), holder.getItemId());
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
RadioButton name;
LocationAreaAdapter mAdapter;
public ViewHolder(View itemView, final LocationAreaAdapter mAdapter) {
super(itemView);
this.mAdapter = mAdapter;
name = itemView.findViewById(R.id.location_area_button);
itemView.setOnClickListener(this);
name.setOnClickListener(this);
}
#Override
public void onClick(View v) {
mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mNames.size());
mAdapter.onItemHolderClick(ViewHolder.this);
}
}
}
when i click on the button the button is not clicked rather recyclerview flashes
When you click to viewholder item select position of current and deselect other viewholder position:
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSelectedItem = position;
notifyDataSetChanged();
}
});
if (mSelectedItem==position ) {
//viewHolder.item.setVisibility(View.VISIBLE);
show itew here.
} else {
// viewHolder.item.setVisibility(View.GONE);
hideitew here.
}

RecyclerView get View by position

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.

Make onClickListener accessible in Activity from RecyclerViewAdapter

Actually in my RecyclerView i'm able to create Child items by programmatically adding view and TextView.
I even have a onClickListener for my parent item from the same RecyclerView and i've added a onClick method for my Child view's but now my main issue is how can i use the Child onClick in my Activity?
Here is my Adapter code
public class AdapterPTERM extends RecyclerView.Adapter<AdapterPTERM.ExampleViewHolder> {
private List<ItemPTERM> mExampleList;
private final LayoutInflater mInflater;
private OnItemClickListener mListener;
// ONCLICK FOR THE CHILD ITEMS
private View.OnClickListener varientClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getTag()!= null){
int position = (int) v.getTag();
}
}
};
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
#NonNull
#Override
public ExampleViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_pterm,parent,false);
return new ExampleViewHolder(v,mListener);
}
AdapterPTERM(Context context, List<ItemPTERM> exampleList){
mExampleList = exampleList;
mInflater = LayoutInflater.from(context);
}
#Override
public void onBindViewHolder(#NonNull final ExampleViewHolder holder, final int position) {
final ItemPTERM item = mExampleList.get(position);
holder.desc.setText(item.getBtnName());
holder.qta.setText(String.valueOf(item.getQuant()));
holder.variantsContainer.removeAllViews();
// CREATING CHILD ITEM
List<Variant> variants = item.getVariants();
if (variants != null && variants.size() > 0){
for(Variant v : variants){
View vView = mInflater.inflate(R.layout.variant_layout,holder.variantsContainer,false);
TextView nameTV = vView.findViewById(R.id.variant_name);
nameTV.setText(v.getName());
vView.setTag(position);
vView.setOnClickListener(varientClickListener);
holder.variantsContainer.addView(vView);
}
}
// NOT IMPORTANT (CHANGING FIELDS COLOR)
if(position % 2 == 0 ){
holder.itemView.setBackgroundColor(Color.parseColor("#C0C0C0"));
}else if(position % 2 == 1){
holder.itemView.setBackgroundColor(Color.parseColor("#D3D3D3"));
}
}
#Override
public int getItemCount() {
return mExampleList.size();
}
public class ExampleViewHolder extends RecyclerView.ViewHolder {
public TextView desc;
public TextView qta;
private LinearLayout variantsContainer;
ExampleViewHolder(View itemView, final OnItemClickListener listener) {
super(itemView);
desc = itemView.findViewById(R.id.Desc);
qta = itemView.findViewById(R.id.Qta);
variantsContainer = itemView.findViewById(R.id.ll_child_items);
// onClick method for Parent Item
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
public void removeItem(int position) {
mExampleList.remove(position);
notifyItemRemoved(position);
}
public void removeVariant(int position,int positionbtn){
mExampleList.get(positionbtn).getVariants().remove(position);
notifyDataSetChanged();
}
}
While here is my code from the Activity where i build my RecyclerView and here i'm using the onClick for the parent for make appear an AlertDialog but i would be able to make appear that AlertDialog by clicking onChild instead of parent.
public void buildTopRecyclerView() {
mRecyclerViewTOP = findViewById(R.id.listView);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
exampleAdapter = new AdapterPTERM(this,dummyDataItems);
mRecyclerViewTOP.setLayoutManager(mLayoutManager);
mRecyclerViewTOP.setAdapter(exampleAdapter);
mRecyclerViewTOP.setHasFixedSize(true);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
if (direction == ItemTouchHelper.RIGHT) {
customAllertDelete(position);
exampleAdapter.notifyItemChanged(position);
}
if (direction == ItemTouchHelper.LEFT) {
customAllertQuantity(position);
exampleAdapter.notifyItemChanged(position);
}
}
}).attachToRecyclerView(mRecyclerViewTOP);
exampleAdapter.setOnItemClickListener(new AdapterPTERM.OnItemClickListener() {
#Override
public void onItemClick(int position) {
if (dummyDataItems.get(position).getVariants() != null) {
customAlertVar(position);
}else {
//
}
}
});
}
SOLVED
I just had to remove
// ONCLICK FOR THE CHILD ITEMS
private View.OnClickListener varientClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getTag()!= null){
int position = (int) v.getTag();
}
}
};
From my adapter as it was handling another click and was blocking the AlertDialog and even removed the
vView.setTag(position);
vView.setOnClickListener(varientClickListener);

Categories

Resources