I am trying to implement a horizontal recycleview with right and left arrow indicators. So what happens is if one clicks the right arrow next item should appear and if one clicks the left arrow the previous item should appear and also at the end of the list the left arrow should disappear. I have no Idea how ti implement this. can someone help me out? Below is my Horizontal Recyclerview adapter.
public class DialogRecyclerViewAdapter extends RecyclerView.Adapter<DialogRecyclerViewAdapter.ViewHolder> {
Context context;
List<UploadImage> dataAdapters;
private SharedPreferences.Editor mSharedPrefEditor;
ImageLoader imageLoader;
public DialogRecyclerViewAdapter(List<UploadImage> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
final UploadImage dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImage(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.drawable.loading_1,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImage(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getBrand_name());
Viewholder.garment_price.setText(dataAdapterOBJ.getGarment_price());
Viewholder.VollyImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(MihuChatApplication.getInstance().getContext());
mSharedPrefEditor = sharedPref.edit();
mSharedPrefEditor.putString(Constants.KEY_FROM_CHAT, "fromChatWIndow").apply();
Intent i=new Intent(MihuChatApplication.getInstance().getContext(), DetailsNewActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//PACK DATA TO SEND
i.putExtra("image_title",dataAdapterOBJ.getGarment_name());
i.putExtra("image_url",dataAdapterOBJ.getImage_full());
i.putExtra("desc_text", dataAdapterOBJ.getDesc_text());
//i.putExtra("image_url2", imageLarger);
i.putExtra("image_price", dataAdapterOBJ.getGarment_price());
//i.putExtra("disc_price", disc_price);
//open activity
MihuChatApplication.getInstance().getApplicationContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView, garment_price;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
garment_price = (TextView) itemView.findViewById(R.id.garment_price);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
Thanks in advance.
Try the following
here img_LeftScroll is the left imageview and img_right_scroll is the right imageview between the horizontal list, rv_horizontal is the horizontallist view
then onclick of the image view do the below, hope it works
img_LeftScroll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (horizontalLayoutManagaer.findFirstVisibleItemPosition() > 0) {
rv_horizontal.smoothScrollToPosition(horizontalLayoutManagaer.findFirstVisibleItemPosition() - 1);
} else {
rv_horizontal.smoothScrollToPosition(0);
}
}
});
img_right_scroll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rv_horizontal.smoothScrollToPosition(horizontalLayoutManagaer.findLastVisibleItemPosition() + 1);
}
});
Horizontal Recycler view with left and right arrow Indicators --I have Done this By creating a custom Layout with recyclerVIew and two arrow images --
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
switch (newState) {
case SCROLL_STATE_DRAGGING:
//Indicated that user scrolled.
programaticallyScrolled = false;
break;
case SCROLL_STATE_IDLE:
if (!programaticallyScrolled) {
currentVisibleItem = linearLayoutManager.findFirstCompletelyVisibleItemPosition();
handleWritingViewNavigationArrows(false);
}
break;
default:
break;
}
}
});
Hide/Show navigation arrows
/**
* Handles the arrows visibility based on current visible items and scrolls the
* current visibility item based on param scroll.
*
* Scroll - is False if User scrolls the Reycler Manually
* - is True means User used arrows to navigate
*
* #param scroll
*/
private void handleWritingViewNavigationArrows(boolean scroll) {
if (currentVisibleItem == (recyclerView.getAdapter().getItemCount() - 1)) {
rightArrow.setVisibility(View.GONE);
leftArrow.setVisibility(View.VISIBLE);
} else if (currentVisibleItem != 0) {
rightArrow.setVisibility(View.VISIBLE);
leftArrow.setVisibility(View.VISIBLE);
} else if (currentVisibleItem == 0) {
leftArrow.setVisibility(View.GONE);
rightArrow.setVisibility(View.VISIBLE);
}
if (scroll) {
recyclerView.smoothScrollToPosition(currentVisibleItem);
}
}
Check the example for the reference hope it helps u
https://github.com/RameshBhupathi/RecyclerViewWithLeftAndRightArrowsExample
This code works in my case:
btn_to_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p = linearLayoutManager.findFirstVisibleItemPosition() - 1;
recyclerview.smoothScrollToPosition( p);
checkVisibility();
}
});
btn_to_left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
p = linearLayoutManager.findLastVisibleItemPosition() + 1;
recyclerview.smoothScrollToPosition(p);
checkVisibility();
}
});
public void checkVisibility() {
if (p < 1) {
btn_to_right.setVisibility(View.GONE);
btn_to_left.setVisibility(View.VISIBLE);
} else if (p >= (recyclerview.getAdapter().getItemCount() - 1)) {
btn_to_right.setVisibility(View.VISIBLE);
btn_to_left.setVisibility(View.GONE);
} else {
btn_to_right.setVisibility(View.VISIBLE);
btn_to_left.setVisibility(View.VISIBLE);
}
}
Much simpler approach for hiding/showing arrows:
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrollStateChanged(#NonNull RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if (manager.findFirstCompletelyVisibleItemPosition()==0){
leftArrow.setVisibility(View.INVISIBLE);
}else{
leftArrow.setVisibility(View.VISIBLE);
}
if (manager.findLastCompletelyVisibleItemPosition()==list.size()-1){
rightArrow.setVisibility(View.INVISIBLE);
}else
rightArrow.setVisibility(View.VISIBLE);
}
#Override
public void onScrolled(#NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
}
});
Related
I built a simple quiz app with sqlite database
There is some quiz headers and into this quiz headers we have some questions that show by recycler view. All questions have one question title and 4 answers and one correct answer. user chooses the radio button answers and after that click on confirm button that is located as item at the bottom of recycler view.
I can catch the correct answer with a simple way and send it to the activity with an interface. But i want to show the correct and wrong answers with changing the radio buttons color but I can't create another method and change the view holder items because I can't access to the view holders outside of 'onBindViewHolder' method . I can handle this with another adapter . I mean I can create a fake adapter that just show answers . Is it a right way ?
This is my code. It's a little messy. Sorry about that
public class QuestionRecyclerAdapter extends RecyclerView.Adapter<QuestionRecyclerAdapter.ViewHolder> {
private Context context;
private List<QuestionHolder> questionHolders;
private OnQuestionAnswerSelect onQuestionAnswerSelect;
private OnConfirmButtonClicked onConfirmButtonClicked;
public QuestionRecyclerAdapter(Context context, List<QuestionHolder> questionHolders) {
this.context = context;
this.questionHolders = questionHolders;
}
public void setOnQuestionAnswerSelect(OnQuestionAnswerSelect onQuestionAnswerSelect) {
this.onQuestionAnswerSelect = onQuestionAnswerSelect;
}
public void setOnConfirmButtonClicked(OnConfirmButtonClicked onConfirmButtonClicked){
this.onConfirmButtonClicked = onConfirmButtonClicked;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView;
if (viewType == R.layout.question_item)
itemView = LayoutInflater.from(context).inflate(R.layout.question_item, parent, false);
else
itemView = LayoutInflater.from(context).inflate(R.layout.question_recycler_confirm_button, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position != questionHolders.size()) {
QuestionModel currentModel = questionHolders.get(position).getQuestionModel();
holder.txtQuestion.setText(currentModel.getTitle());
holder.rBtnAnswer1.setText(currentModel.getOption1());
holder.rBtnAnswer2.setText(currentModel.getOption2());
holder.rBtnAnswer3.setText(currentModel.getOption3());
holder.rBtnAnswer4.setText(currentModel.getOption4());
if (onQuestionAnswerSelect != null) {
holder.questionRadioGroup.setOnCheckedChangeListener((v, i) -> {
RadioButton rBtnSelected = holder.questionRadioGroup.findViewById(holder.questionRadioGroup.getCheckedRadioButtonId());
int selectedRadioIndex = holder.questionRadioGroup.indexOfChild(rBtnSelected) + 1;
if (selectedRadioIndex == questionHolders.get(position).getQuestionModel().getCorrectNumber()) {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), true);
} else {
onQuestionAnswerSelect.onAnswerSelected(questionHolders.get(position).get_id(), false);
}
});
}
}else {
holder.btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (onConfirmButtonClicked != null)
onConfirmButtonClicked.onConfirmClicked();
}
});
}
}
#Override
public int getItemCount() {
return questionHolders.size() + 1;
}
#Override
public int getItemViewType(int position) {
return (position == questionHolders.size()) ? R.layout.question_recycler_confirm_button : R.layout.question_item;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtQuestion;
public RadioGroup questionRadioGroup;
public RadioButton rBtnAnswer1;
public RadioButton rBtnAnswer2;
public RadioButton rBtnAnswer3;
public RadioButton rBtnAnswer4;
public Button btnConfirm;
public ViewHolder(#NonNull View itemView) {
super(itemView);
txtQuestion = itemView.findViewById(R.id.txtQuestion);
questionRadioGroup = itemView.findViewById(R.id.questionRadioGroup);
rBtnAnswer1 = itemView.findViewById(R.id.rBtnAnswer1);
rBtnAnswer2 = itemView.findViewById(R.id.rBtnAnswer2);
rBtnAnswer3 = itemView.findViewById(R.id.rBtnAnswer3);
rBtnAnswer4 = itemView.findViewById(R.id.rBtnAnswer4);
btnConfirm = itemView.findViewById(R.id.btnConfirm);
}
}
}
public class QuizActivity extends AppCompatActivity {
RecyclerView questionRecyclerView ;
QuestionRecyclerAdapter adapter ;
QuestionDatabaseHelper questionDatabaseHelper ;
Map<Integer,Boolean> answeredRecords = new HashMap<>();
int score ;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
questionRecyclerView = findViewById(R.id.questionRecyclerView);
questionDatabaseHelper = new QuestionDatabaseHelper(this);
int selectedId = getIntent().getIntExtra(Constants.SELECTED_ID,0);
score = 0 ;
List<QuestionHolder> questionHolders = questionDatabaseHelper.getAllQuestionHoldersById(selectedId);
adapter = new QuestionRecyclerAdapter(this,questionHolders);
questionRecyclerView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
questionRecyclerView.setAdapter(adapter);
adapter.setOnQuestionAnswerSelect(new OnQuestionAnswerSelect() {
#Override
public void onAnswerSelected(int questionNumber, boolean isCorrect) {
answeredRecords.put(questionNumber,isCorrect);
}
});
adapter.setOnConfirmButtonClicked(new OnConfirmButtonClicked() {
#Override
public void onConfirmClicked() {
score = 0 ;
for(Map.Entry<Integer,Boolean> item : answeredRecords.entrySet()){
if (item.getValue())
score++;
}
Log.e("THE SCORE IS ", String.valueOf(score));
}
});
}
private void displayRecords(){
for(Map.Entry<Integer,Boolean> item : answeredRecords.entrySet()){
Log.e("AAA",item.getKey() + " : " + item.getValue());
}
}
}
Make a function in adapter and send holder to activity by calling that function.
first make viewholder named holder1.
ViewHolder holder1;
then at the onBindViewHolder method add this:
holder1 = holder;
public ViewHolder getHolder(){
return holder1;
}
now you can use it in your Activity like this:
adapter.getHolder.rBtnAnswer1.setBackgroundColor(Color.parseColor("#FFFFFF")); //this is a example.
I have a Recyclerview and there are Imageviews in it. When I click any of image, I want to make visible a number of information about image on the image.
Well, I did it but it seems everything's happening randomly... When I click first image, informations appearing on the second, when I click on the second its working normally and when I click third, nothing happening etc.
Here is some of my code;
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
myViewHolder = new MyViewHolder(view);
myViewHolder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isUp) {
slideDown(myViewHolder.infoView);
} else {
slideUp(myViewHolder.infoView);
}
isUp = !isUp;
}
});
return myViewHolder;
}
class MyViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
init();
}
void init() {
imageView = itemView.findViewById(R.id.imageViewID);
...
}
}
It seems I should group some elements or is there any better idea, way ?
Slide method;
// slide the view from below itself to the current position
public void slideUp(View view) {
view.setVisibility(View.VISIBLE);
infoView.animate().alpha(1.0f).setDuration(500);
ScaleAnimation animate = new ScaleAnimation(
1f, 1f, // Start and end values for the X axis scaling
0f, 1f, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF, 0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 1f); // toYDelta
animate.setDuration(800);
animate.setFillAfter(true);
view.startAnimation(animate);
}
I moved onClickListener method to onBindViewHolder and thats what make sense but result did not change.
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView_name.setText(nameElement.get(position).text());
Picasso.get().load(imageElement.get(position).absUrl("src")).fit().into(holder.imageView);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isUp) {
myViewHolder.slideDown(myViewHolder.infoView);
} else {
myViewHolder.slideUp(myViewHolder.infoView);
}
isUp = !isUp;
}
});
}
You need to add slideUp slideDown methods in MyViewHolder class
and I think no need to implement click listener in onBindViewHolder, just put it in the init function.
void init() {
imageView = itemView.findViewById(R.id.imageViewID);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (isUp) {
slideDown(v);
} else {
slideUp(v);
}
isUp = !isUp;
}
});
}
hope it works!!!
You should add listener for the ViewHolder in onBindViewHolder, and not onCreateViewHolder
First of all, it's better to define onClickListener in onBindViewHolder
Second, store the data on a POJO class, and save last states,
so you can keep the last state of an item(isUP or !)
for example, you have this model:
class ImageModel {
private String imageURI;
private Boolean isUP ;
//getter setters
}
then if you pass a list of ImageModel into your adapter, you can easily change the isUP
and on your adapter change the state of imageviews based on isUP
if (model.isUp) {
slideDown(myViewHolder.infoView);
} else {
slideUp(myViewHolder.infoView);
}
I have an activity with a RecyclerView and a button that is disabled at first. The elements of the RV are selectable, and I want the button to be enabled only after an element was selected. I tried to set addOnItemTouchListener on the recyclerview, the problem is that it is also called when scrolling through the list.
Here is my Adapter:
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
private ArrayList<ClusterItem> mListOfClusters;
private OnItemClickListener mListener;
//index
int row_index = -1; //Default no row chosen
public interface OnItemClickListener{
//delete
void onDeleteCluster(int position);
//edit
void onEditCluster(int position);
//select
void onClick(View view, int position);
}
public void setOnItemClickListener(OnItemClickListener listener){mListener = listener;}
public static class ClusterListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView mClusterName;
public TextView mClusterMembers;
public ImageView mDeleteCluster;
public ImageView mEditCluster;
//This
private OnItemClickListener itemClickListener;
public void setItemClickListener(OnItemClickListener listener){
this.itemClickListener = listener;
}
public ClusterListViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
mClusterName = itemView.findViewById(R.id.tv_clusters_name_cluster_list);
mClusterMembers = itemView.findViewById(R.id.tv_clusters_members_cluster_list);
mDeleteCluster = itemView.findViewById(R.id.iv_delete_cluster);
mEditCluster = itemView.findViewById(R.id.iv_edit_cluster);
mDeleteCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onDeleteCluster(position);
}
}
}
});
mEditCluster.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onEditCluster(position);
}
}
}
});
//used for highlighting item
itemView.setOnClickListener(this);
}
//This
#Override
public void onClick(View v) {
itemClickListener.onClick(v, getAdapterPosition());
}
}
public CLusterListAdapter(ArrayList<ClusterItem> listOfClusters ){ mListOfClusters = listOfClusters;}
#NonNull
#Override
public ClusterListViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.chose_your_cluster_list_item, viewGroup, false);
ClusterListViewHolder clusterListViewHolder = new ClusterListViewHolder(view, mListener);
return clusterListViewHolder;
}
#Override
public void onBindViewHolder(#NonNull ClusterListViewHolder clusterListViewHolder, int i) {
ClusterItem currentCluster = mListOfClusters.get(i);
clusterListViewHolder.mClusterName.setText(currentCluster.getClustersName());
clusterListViewHolder.mClusterMembers.setText(currentCluster.getClustersMembers());
clusterListViewHolder.mClusterMembers.setSelected(true);
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
SpTAGs.selectedClusterPosition = position;
}
});
//Set highlight color
if(row_index == i) {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#E64A19"));
}else {
clusterListViewHolder.itemView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
}
#Override
public int getItemCount() {
return mListOfClusters.size();
}
}
And here is how I applied the addOnItemTouch
clusterRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
#Override
public boolean onInterceptTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
selectButton.setEnabled(true);
Log.v("MyTAG", "Touch");
return false;
}
#Override
public void onTouchEvent(#NonNull RecyclerView recyclerView, #NonNull MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean b) {
}
});
Any idea how to obtain this? Thank you!
Have a callback from the Adapter to the activity. Enable your button there.
public class CLusterListAdapter extends RecyclerView.Adapter<CLusterListAdapter.ClusterListViewHolder> {
...
interface Listener {
void onItemClick(int position);
}
}
Invoke this on item click
clusterListViewHolder.setItemClickListener(new OnItemClickListener() {
#Override
public void onDeleteCluster(int position) {
//nothing here
}
#Override
public void onEditCluster(int position) {
//nothing here
}
#Override
public void onClick(View view, int position) {
//Select a certain item
row_index = position; //Set row index to selected position
SpTAGs.currentItem = mListOfClusters.get(position); //Set current item is item selection
notifyDataSetChanged(); //Made effect on RecyclerView's Adapter
listener.onItemClick(position); // notify the listener (activity) of the click
SpTAGs.selectedClusterPosition = position;
}
});
In activity:
clusterRecyclerView.addOnItemTouchListener( ... );
clusterRecyclerView.setListener((int position) -> {
// logic to enable button goes here
});
you don't need to use the addOnItemTouchListener here.
just create a methode inside the activity like this
public void VisibleButton(){
yourButton.setVisibility(View.VISIBLE);
/**....*/
}
and just call the methode
VisibleButton()
from your adapter,from where you want your button to be visible, just like this
((YourActivityName)your_ACtivity_Context).VisibleButton();
Here I clicked on the item to change item background and color. I've stored the clicked item value in the database and change the layout color and text color and recreating the adapter and showing the list again while refreshing.
But layout colors not changed when I get its position. Please show the right path to handle the set of background item color always.
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
int I = -1;
int idd = 0;
int II = 0;
Activity activity;
GoogleMap map;
List<VehicleClick> list;
private SparseBooleanArray selectedItems;
public class CarTypesHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
setOnitemclick listener;
public void setOnItemClickListner(setOnitemclick listener) {
this.listener = listener;
}
public CarTypesHolder(View view) {
super(view);
mCarType = (CustomTextView) view.findViewById(R.id.frag_cartypes_inflated_name);
mCarTypeImage = (CircleImageView) view.findViewById(R.id.frag_cartype_inflated_frameImage);
llRoot = (LinearLayout) view.findViewById(R.id.root1);
selectedItems = new SparseBooleanArray();
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.ImageClick(v, getAdapterPosition());
}
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView, Activity activity, GoogleMap map, List<VehicleClick> lists) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
this.activity = activity;
this.map = map;
this.list = lists;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.frag_cartype_inflated_view, parent, false);
return new CarTypesHolder(itemView);
}
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(final CarTypesHolder holder, int position) {
if (list.size() != 0) {
II = Integer.parseInt(list.get(0).RideId);
//setSelection(Integer.parseInt(list.get(0).RideId));
}
if (II == position) {
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#FFFFFF"));
} else {
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
SharedPreferences sharedPreferences = activity.getSharedPreferences("mSelected", Context.MODE_PRIVATE);
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext, PreferenceHandler.SECONDRY_COLOR, "#006fb6"));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(new setOnitemclick() {
#Override
public void ImageClick(View v, int position1) {
I = position1;
notifyDataSetChanged();
try {
if (list.size() != 0) {
VehicleTypeFragment.myAppRoomDataBase.userDao().delete();
list.clear();
}
VehicleClick vehicleClick = new VehicleClick();
vehicleClick.setRideId(String.valueOf(position1));
VehicleTypeFragment.myAppRoomDataBase.userDao().insert(vehicleClick);
list.add(vehicleClick);
} catch (Exception e) {
}
}
});
if (I == position) {
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
Animation bounce = AnimationUtils.loadAnimation(mContext, R.anim.bounce);
holder.llRoot.startAnimation(bounce);
} else {
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
#Override
public long getItemId(int position) {
return CarTypesModelsList.get(position).getID();
}
#Override
public int getItemCount() {
return CarTypesModelsList.size();
}
public void setSelection(int position) {
II = position;
//notifyDataSetChanged();
}
public interface setOnitemclick {
void ImageClick(View view, int position);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
I am not sure what did you mean by refreshing your list. I am guessing that you are recreating the adapter and showing the list again while you are refreshing. Hence the value of I is initialized with -1 each time you are creating the adapter.
You need to do the initialization as follows. Please consider the following is a pseudo code and you need to implement this of your own.
// While declaring your I
// int I = -1;
int I = getTheStoredValueFromDatabase(); // If there is no entry in database, getTheStoredValueFromDatabase function will return -1
I hope you get the idea. You might consider doing the same for other stored values.
for keep track record you need to add Boolean variable in TaxiTypeResponse.Message boolean isClick=false; and toggle this in
holder.setOnItemClickListner(new setOnitemclick() {
#Override
public void ImageClick(View v, int position) {
CarTypesModelsList.get(position).isClick=!CarTypesModelsList.get(position).isClick;
notifyDataSetChanged();
}
}
and modify below code as follow
if (CarTypesModelsList.get(position).isClick) {
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
Animation bounce = AnimationUtils.loadAnimation(mContext, R.anim.bounce);
holder.llRoot.startAnimation(bounce);
}
else{
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
Note: onBindViewHolder() is not a place to implement the click
listeners, but I am just providing you the logic for how to implement
single selection in recyclerView.
Now lets jump to the solution,
simply follow the below tutorial and change the variable, fields, and background according to your need, you have to implement the below method in onBindViewHolder() method of RecyclerView
First, initialize the lastClickedPosition and isclicked
int lastPositionClicked = -1;
boolean isClicked = false;
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.YOUR_VIEW.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// store the position which you have just clicked and you will change the background of this clicked view
lastPositionClicked = position;
isClicked = true;
// need to refresh the adapter
SlabAdapter.this.notifyDataSetChanged();
}
});
// only change the background of last clicked item
if (isClicked && position == lastPositionClicked) {
// change clicked view background color
} else {
// otherwise set the default color for all positions
}
}
let me know if this works.
on BindViewHolder method you'll use this code and set I=0 on globally
#SuppressLint("ResourceType")
#Override
public void onBindViewHolder(final CarTypesHolder holder, int position) {
SharedPreferences sharedPreferences = activity.getSharedPreferences("mSelected", Context.MODE_PRIVATE);
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext, PreferenceHandler.SECONDRY_COLOR, "#006fb6"));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(new setOnitemclick() {
#Override
public void ImageClick(View v, int position1) {
I = position1;
notifyDataSetChanged();
try {
if (list.size() != 0) {
VehicleTypeFragment.myAppRoomDataBase.userDao().delete();
list.clear();
}
VehicleClick vehicleClick = new VehicleClick();
vehicleClick.setRideId(String.valueOf(position1));
VehicleTypeFragment.myAppRoomDataBase.userDao().insert(vehicleClick);
list.add(vehicleClick);
} catch (Exception e) {
}
}
});
if (I == position) {
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
Animation bounce = AnimationUtils.loadAnimation(mContext, R.anim.bounce);
holder.llRoot.startAnimation(bounce);
} else {
holder.llRoot.setBackgroundColor(Color.parseColor("#f3f3f3"));
holder.mCarType.setTextColor(Color.parseColor("#2196F3"));
}
Picasso.with(mContext).load(carTypesModel.getImagePath()).into(holder.mCarTypeImage);
}
I have a simple question. I have a recyclerview with list items, what I can do is highlight the items you click on. My problem is that I don't know how to deselect the previous item the user has clicked on so only 1 item can be selected.
private void loadCategories() {
adapter = new FirebaseRecyclerAdapter<Category, CategoryViewHolder>(
Category.class,
R.layout.categoryaddquestions_layout,
CategoryViewHolder.class,
categories
) {
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final Category model, int position) {
viewHolder.category_name.setText(model.getName());
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
view.setSelected(false);
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}
Here is my view holder I use
public class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public TextView category_name;
public ImageView category_image;
public LinearLayout category_layout;
private ItemClickListener itemClickListener;
public CategoryViewHolder(View itemView) {
super(itemView);
category_layout = itemView.findViewById(R.id.categoryaddquestion_layout);
category_image = itemView.findViewById(R.id.category_image);
category_name = itemView.findViewById(R.id.category_name);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
Create a variable in your adapter called SelectedPosition. On click, update that variable to the adapterPosition and reload the recyclerView.
Make a check in populateViewHolder saying:
if selectedPosition == position {
//highlighted
}
else {
//set back to normal
}
here is my own solution.
#Override
protected void populateViewHolder(CategoryViewHolder viewHolder, final
Category model, int position) {
viewHolder.category_name.setText(model.getName());
if (position == Common.index) {
viewHolder.category_layout.setSelected(true);
} else {
viewHolder.category_layout.setSelected(false);
}
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Common.index = position;
adapter.notifyDataSetChanged();
}
});
}
};
adapter.notifyDataSetChanged();
listCategory.setAdapter(adapter);
}
I just used a Common java class and problem solved with a public static int index