getAdapterPosition not doing what it is supposed to do - java

I have a RecyclerView Fragment to which I added a Filter Search in an edit text. It works, but when I click in a Card of the Recycler, it goes to the wrong detail. My best guess is that it's getting the wrong position from the getAdapterPosition since let's say I have this list {a,b,c,d,e,f,g,h}. when I filter and get two itmes left like {d,g}. If I click d it redirects to a, if I click g it redirects to b.
This is my RecyclerView
public class RecyclerProfile extends Fragment implements
Adapter.AdapterListener, com.example.cake.profiling.Adapter.SearchListener
{
private RecyclerListener recyclerListener;
private List<Profile> profiles = (new DAOProfile()).getProfile();
private Adapter recyclerAdapter= new Adapter(profiles, this);
public RecyclerProfile() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_recycler_profile,
container, false);
RecyclerView recyclerView = view.findViewById(R.id.recyclerProfile);
EditText editText = view.findViewById(R.id.editText);
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
}
#Override
public void afterTextChanged(Editable s) {
filter(s.toString());
}
});
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new
LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerAdapter);
setHasOptionsMenu(true);
return view;
}
private void filter(String text){
ArrayList<Profile> filteredList = new ArrayList<>();
for (Profile profile: profiles){
if (profile.getName().toLowerCase().contains(text.toLowerCase())){
filteredList.add(profile);
}
}
recyclerAdapter.filterList(filteredList);
profiles = new ArrayList<>(filteredList);
}
#Override
public void listen(Profile profile, Integer position) {
recyclerListener.send(profile, position);
}
#Override
public void profileSelected(Profile profile) {
}
//INTERFACE
public interface RecyclerListener {
void send(Profile profile, Integer position);
}
//ON ATTACH
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.recyclerListener = (RecyclerListener) context;
}
}
This is my Adapter
public class Adapter extends RecyclerView.Adapter<Adapter.ProfileViewHolder> {
private List<Profile> profiles;
private AdapterListener adapterListener;
//CONSTRUCTOR
public Adapter(List<Profile> profiles,AdapterListener adapterListener) {
this.profiles = profiles;
this.adapterListener = adapterListener;
}
#NonNull
#Override
public Adapter.ProfileViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.card_profile, parent, false);
ProfileViewHolder profileViewHolder = new ProfileViewHolder(view);
return profileViewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ProfileViewHolder holder, int position) {
Profile profile = profiles.get(position);
holder.setter(profile);
}
#Override
public int getItemCount() {
return profiles.size();
}
public void filterList (ArrayList<Profile> filteredList){
profiles = filteredList;
notifyDataSetChanged();
}
//VIEWHOLDER
class ProfileViewHolder extends RecyclerView.ViewHolder{
private ImageView image;
private TextView name;
public ProfileViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameProfile);
image = itemView.findViewById(R.id.imageProfile);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Profile profile = profile.get(getAdapterPosition());
adapterListener.receive(profile, getAdapterPosition());
}
});
}
public void setter (Profile profile){
name.setText(profile.getName());
image.setImageResource(profile.getImage());
}
}
public interface AdapterListener {
void receive(Profile profile, Integer position);
}
}

getAdapterPosition()
this will return the position of the item of current data set. This is what I'd do
class ProfileViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView image;
private TextView name;
Profile mProfile;
public ProfileViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.nameProfile);
image = itemView.findViewById(R.id.imageProfile);
name.setOnClickListener(this);
image.setOnClickListener(this);
}
public void setter (Profile profile){
if(profile != null) {
mProfile = profile;
name.setText(mProfile.getName());
image.setImageResource(mProfile.getImage());
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.item_nameProfile:
case R.id.item_imageProfile:
for(int i = 0 ; i < profiles.size() ; i++) {
if(profiles.get(i).getName().equalsIgnoreCase(mProfile.getName()) {
adapterListener.receive(profiles.get(i), i);
break;
}
}
break;
}
}
public interface AdapterListener {
void receive(Profile profile, Integer position);
}
}

Related

Recycleview cardview Onclick duplicate effects when scrolling

I'm making my first app (calendar),
clicking the cardview item applies the same effect (changing Textview text color and Imageview background) to other items when scrolling the recycleview
in the main activity
RecyclerView daysRecyclerView;
DaysAdapter daysAdapter;
private RecyclerView.LayoutManager horizontalLayout;
ArrayList<DaysModel> daysModels;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
daysModels = getDaysList();
initDaysRecycleview();
}
private void initDaysRecycleview(){
daysRecyclerView = findViewById(R.id.daysRecyclerView);
daysRecyclerView.setHasFixedSize(true);
horizontalLayout = new LinearLayoutManager(this,RecyclerView.HORIZONTAL,false);
daysAdapter = new DaysAdapter(daysModels);
daysRecyclerView.setLayoutManager(horizontalLayout);
daysRecyclerView.setAdapter(daysAdapter);
daysAdapter.setOnItemClickListener(new DaysAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
dayClickHandler(position, 1);
}
});
}
public void dayClickHandler(int position, int change){
daysModels.get(position).changeDayHighlight(change);
daysAdapter.notifyItemChanged(position);
}
private ArrayList<DaysModel> getDaysList(){
//Not accurate used for testing
ArrayList<DaysModel> models = new ArrayList<DaysModel>();
String[] dayName ={"SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON","TUE","WED","THU","FRI","SAT","SUN","MON"};
int i,j;
for (i = 0;i <dayName.length;i++){
j =i+1;
models.add(new DaysModel(dayName[i], j, 0, false));
}
return models;
}
I'm using an interface for the onClickListener.
ViewHolder
public class DaysViewHolder extends RecyclerView.ViewHolder {
TextView hDayName,hDayNumber;
ImageView currentDayHighlight;
CardView dayCard;
public DaysViewHolder(View itemView, DaysAdapter.OnItemClickListener listener) {
super(itemView);
this.hDayName = itemView.findViewById(R.id.dayName);
this.hDayNumber = itemView.findViewById(R.id.dayNumber);
this.currentDayHighlight = itemView.findViewById(R.id.dayHihlight);
this.dayCard = itemView.findViewById(R.id.dayCard);
dayCard.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
listener.onItemClick(position);
}
}
}
});
}
}
Adapter
public class DaysAdapter extends RecyclerView.Adapter<DaysViewHolder> {
Context context;
ArrayList<DaysModel> daysModels;
OnItemClickListener mListener;
public interface OnItemClickListener{
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener){
mListener = listener;
}
public DaysAdapter(ArrayList<DaysModel> daysModels) {
this.daysModels = daysModels;
}
#NonNull
#Override
public DaysViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.day_card,parent,false);
DaysViewHolder daysViewHolder = new DaysViewHolder(view, mListener);
return daysViewHolder;
}
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}
}
#Override
public int getItemCount() {
return daysModels.size();
}
}
sorry for the long code text, I've just started and I am already struggling.
All you need is to set else part for you if condition in bind method of Adapter class.
So change your bind method to something like this:
#Override
public void onBindViewHolder(#NonNull DaysViewHolder holder, int position) {
DaysModel currentItem = daysModels.get(position);
holder.hDayName.setText(currentItem.getDayName());
holder.hDayNumber.setText(String.valueOf(currentItem.getDayNumber()));
if(currentItem.isDayHighlighted() == 1){
holder.currentDayHighlight.setBackgroundResource(R.drawable.tiny_background);
holder.hDayNumber.setTextColor(Color.BLACK);
}else{
holder.currentDayHighlight.setBackgroundResource(/*what ever you want for default situation*/);
holder.hDayNumber.setTextColor(/* for example Color.White*/);
}
}

how to make the progress bar invisible in recyclerview

There is a list of pictures made through RecyclerView. When you click on a picture while it is being transferred to the next activity, a ProgressBar should be displayed. When there is a return to the activity of the image selection, the ProgressBar also remains visible, although it must be hidden.
As I did below, the progress bar becomes invisible only in the first image, but in the rest it does not work. I can’t understand why
in my project there are such classes as:
interface
public interface ImageOnC {
void onClick(int position);
}
ImageViewHolder
public class ImageViewHolder extends RecyclerView.ViewHolder {
public ImageView imageView;
private ImageOnC imageOnC;
public ImageButton imageButton;
public ProgressBar progressBar;
public void setImageOnC(ImageOnC imageOnC) {
this.imageOnC = imageOnC;
}
public ImageViewHolder(#NonNull final View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.image_outline);
progressBar = itemView.findViewById(R.id.progr);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imageOnC.onClick(getAdapterPosition());
progressBar.setVisibility(View.VISIBLE);
}
});
}
}
ImageAdabter
public class ImageAdabter extends RecyclerView.Adapter<ImageViewHolder> {
private Context mContext;
private List<Integer> listImages;
public ImageAdabter(Context mContext){
this.mContext = mContext;
this.listImages = getImages();
}
private List<Integer> getImages() {
List<Integer> results = new ArrayList<>();
results.add(R.drawable.outline1);
results.add(R.drawable.outline2);
results.add(R.drawable.outline3);
results.add(R.drawable.outline4);
results.add(R.drawable.outline5);
results.add(R.drawable.outline6);
results.add(R.drawable.outline7);
results.add(R.drawable.outline8);
results.add(R.drawable.outline9);
results.add(R.drawable.outline10);
return results;
}
#NonNull
#Override
public ImageViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_images,parent,false);
return new ImageViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final ImageViewHolder holder, final int position) {
holder.imageView.setImageResource( listImages.get(position));
holder.setImageOnC(new ImageOnC() {
#Override
public void onClick(int position) {
Common.PICTURE_SELECTED = listImages.get(position);
mContext.startActivity(new Intent(mContext, Colorful.class));
}
});
#Override
public void onBindViewHolder(#NonNull ImageViewHolder holder, int position, List<Object>payload){
//if so, then the progress bar only works for the first image in recyclerview
if(!payload.isEmpty()){
if(payload.get(position) instanceof Integer)
holder.progressBar.setVisibility(View.GONE);
}
else super.onBindViewHolder(holder, position, payload);
}
#Override
public int getItemCount() {
return listImages.size();
}
}
I add this to activity
private void initView() {
recyclerView = findViewById(R.id.recycle_view_images);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adabter = new ImageAdabter(this);
recyclerView.setAdapter(adabter);
}
#Override
public void onResume() {
super.onResume();
if (adabter != null) {
adabter.notifyItemChanged(position, position);
}
}
in xml file use Progress bar visibility gone

Problem with display RecyclerView using BottomSheetDialog

I am not able to bind recyclerview with adapter using BottomSheetDialog
Here is my MainActivity
public class MainActivity extends AppCompatActivity {
BottomAppBar bottomAppBar;
FloatingActionButton floatingActionButton;
ImageView emptyView;
private RecyclerView recyclerView;
private List<AppModel> appModelResult = new ArrayList<>();
private AppAdapter appAdapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emptyView = findViewById(R.id.empty_view);
bottomAppBar = findViewById(R.id.bottom_app_bar);
setSupportActionBar(bottomAppBar);
floatingActionButton =findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddAppDialog addAppDialog = new AddAppDialog();
addAppDialog.show(getSupportFragmentManager(),"AddBottomSheet");
}
});
bottomAppBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheet = new BottomSheetDialog();
bottomSheet.show(getSupportFragmentManager(), "BottomSheet");
}
});
//RecyclerView Binding
recyclerView = findViewById(R.id.app_list);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
appAdapter = new AppAdapter(appModelResult);
recyclerView.setAdapter(appAdapter);
appAdapter.setItems(appModelResult);
if(appAdapter.getItemCount() == 0){
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}else{
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
}
}}
And here is my BottomSheetDialog, where i input 2 EditText and a Spinner.Taping on Save Button should display written data on the main screen, however there is nothing on a display.
public class AddAppDialog extends BottomSheetDialog implements AdapterView.OnItemSelectedListener {
static TextInputEditText appUrl;
TextInputEditText appDesc;
MaterialButton saveButton;
Spinner spinnerCategory;
AppModel appModel = new AppModel();
List<AppModel> appModelResult = new ArrayList<>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_bottomsheet_add,container,false);
appUrl = v.findViewById(R.id.app_url);
appDesc = v.findViewById(R.id.app_desc);
saveButton = v.findViewById(R.id.save_button);
spinnerCategory = v.findViewById(R.id.spinner_category);
List<String> categories = new ArrayList<String>();
categories.add(0,"Choose category");
categories.add("Education");
categories.add("Entertainment");
categories.add("Games");
categories.add("Health");
categories.add("Personalization");
categories.add("Social");
categories.add("Tools");
ArrayAdapter<CharSequence> adapter = new ArrayAdapter(getActivity().getApplicationContext(),android.R.layout.simple_spinner_item,categories);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerCategory.setAdapter(adapter);
spinnerCategory.setOnItemSelectedListener(this);
appUrl.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) { }
#Override
public void afterTextChanged(Editable s) {
new Parse().execute();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(appUrl.getText().toString().trim().length() != 0) {
appModel.setAppDesc(appDesc.getText().toString());
appModelResult.add(0,new AppModel(Parse.eImage,Parse.eName,appModel.getAppCategory(),appModel.getAppDesc()));
System.out.println(appModelResult.get(0).getImage());
System.out.println(appModelResult.get(0).getAppText());
System.out.println(appModelResult.get(0).getAppCategory());
System.out.println(appModelResult.get(0).getAppDesc());
dismiss();
}else{
appUrl.setError("URL is required :)");
}
}
});
return v;
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(parent.getItemAtPosition(position).equals("Choose category")){
}else{
String selectedCategory = parent.getItemAtPosition(position).toString();
appModel.setAppCategory(selectedCategory);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}}
Finally, my Adapter for RecyclerView looks like that:
public class AppAdapter extends RecyclerView.Adapter<AppAdapter.AppViewHolder> {
private List<AppModel> mAppModelList;
public AppAdapter(List<AppModel> appModelList) {
mAppModelList = appModelList;
}
public static class AppViewHolder extends RecyclerView.ViewHolder{
public ImageView appImage;
public TextView appText,appCategory,appDesc;
public AppViewHolder(#NonNull View itemView) {
super(itemView);
appImage = itemView.findViewById(R.id.app_image_list);
appText = itemView.findViewById(R.id.app_text_list);
appCategory = itemView.findViewById(R.id.app_category_list);
appDesc = itemView.findViewById(R.id.app_desc_list);
}
}
public void setItems(List<AppModel> items){
mAppModelList.addAll(items);
notifyDataSetChanged();
}
public void clearItems(){
mAppModelList.clear();
notifyDataSetChanged();
}
#NonNull
#Override
public AppViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_list,parent,false);
AppViewHolder appViewHolder = new AppViewHolder(v);
return appViewHolder;
}
#Override
public void onBindViewHolder(#NonNull AppViewHolder holder, int position) {
AppModel appModel = mAppModelList.get(position);
holder.appText.setText(appModel.getAppText());
holder.appCategory.setText(appModel.getAppCategory());
holder.appDesc.setText(appModel.getAppDesc());
Picasso.get().load(appModel.getImage()).into(holder.appImage);
}
#Override
public int getItemCount() {
return mAppModelList.size();
}}
I think that XML files are OK,therefore i have not pasted it here, and the only problem is regarding to binding process.
Solved it adding RecyclerView in Fragment and refreshing list via detach & attach
getActivity().getSupportFragmentManager().beginTransaction().detach(getFragmentManager().findFragmentById(R.id.recycler_fragment)).commitNowAllowingStateLoss();
getActivity().getSupportFragmentManager().beginTransaction().attach(new RecyclerFragment()).commitAllowingStateLoss();
Attention!
In order reload fragment use only dynamic fragments.

Recycle view adapter how i highlighted single item on click

I'm using recycler view and I implement this functionality as per project requirement. But in my case item is highlighted but not unhighlighted again.
I was confused where I click the item for creating the clicking functionality, and how to unhighlighted the item. Please suggest me the right way to solve the code
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
setOnitemclick listener;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
int I=-1;
public class CarTypesHolder extends RecyclerView.ViewHolder {
public CustomTextView mCarType;
public CircleImageView mCarTypeImage;
LinearLayout llRoot;
CardView cardView;
private SparseBooleanArray selectedItems = new SparseBooleanArray();
setOnitemclick listener;
public CarTypesHolder(final 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);
cardView=(CardView) view.findViewById(R.id.cardf);
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
}
public void setOnItemClickListner(setOnitemclick listener12) {
listener=listener12;
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#Override
public CarTypesHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
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, final int position) {
TaxiTypeResponse.Message carTypesModel = CarTypesModelsList.get(position);
I=CarTypesModelsList.get(position).getID();
holder.mCarType.setText(carTypesModel.getName());
holder.mCarTypeImage.setBackgroundResource(R.drawable.wait);
int color = Color.parseColor(PreferenceHandler.readString(mContext,PreferenceHandler.SECONDRY_COLOR,"#006fb6"));
holder.llRoot.setSelected(selectedItems.get(position, false));
holder.mCarType.setTextColor(color);
holder.setOnItemClickListner(listener);
holder. llRoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I=position;
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
notifyDataSetChanged();
}
});
if (I==position)
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#999999"));
}
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(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(int position, String Name,String Description,int id);
void ImageClickfade(int position, String Name,String Description,int id);
}
#Override
public int getItemViewType(int position) {
return position;
}
}
I'll use to update gradle
maven { url "https://maven.google.com" }
and update the code
public class LoadVehicleTypeAdapter extends RecyclerView.Adapter<LoadVehicleTypeAdapter.CarTypesHolder> {
private List<TaxiTypeResponse.Message> CarTypesModelsList;
private Context mContext;
VehicleTypeView vehicleTypeView;
int I=-1;
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);
cardView=(CardView) view.findViewById(R.id.cardf);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listener.ImageClick(v,getAdapterPosition());
}
}
public LoadVehicleTypeAdapter(Context context, List<TaxiTypeResponse.Message> CarTypesModelsList, VehicleTypeView vehicleTypeView) {
this.CarTypesModelsList = CarTypesModelsList;
mContext = context;
this.vehicleTypeView = vehicleTypeView;
}
#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) {
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();
System.out.println("11100011111");
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
});
if (I==position)
{
System.out.println("11100011111....");
holder.llRoot.setBackgroundColor(Color.parseColor("#999999"));
holder.mCarType.setTextColor(Color.parseColor("#ffffff"));
}
else
{
System.out.println("11100011111----");
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(LinearLayout imageView,CustomTextView textView,boolean value,int position){
if(value){
imageView.setBackgroundColor(Color.parseColor("#999999"));
textView.setTextColor(Color.parseColor("#FFFFFF"));
}else{
System.out.println("11111111111111111000000111111111111");
imageView.setBackgroundColor(Color.parseColor("#f3f3f3"));
textView.setTextColor(Color.parseColor("#2196F3"));
}
}
public interface setOnitemclick{
void ImageClick(View view,int position);
}
#Override
public int getItemViewType(int position) {
return position;
}
}

onClickListener in RecyclerView.ViewHolder

I've got a RecyclerView.ViewHolder and RecyclerView.Adapter, I need after click on item and then send information about this item to another Activity.
PlacesAdapter.java
public class PlacesAdapter extends RecyclerView.Adapter<PlacesViewHolder> {
private PlacesActivity placesActivity;
Context context;
private int position;
List<Places> places;
public PlacesAdapter(List<Places> places) {
this.places = places;}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PlacesViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.places_view, viewGroup, false);
PlacesViewHolder pvh = new PlacesViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PlacesViewHolder personViewHolder, int i) {
personViewHolder.name.setText(places.get(i).name);
personViewHolder.address.setText(places.get(i).address);
Picasso.with(personViewHolder.itemView.getContext())
.load(places.get(i).photo)
.into(personViewHolder.getPhoto());
}
#Override
public int getItemCount() {
return places.size();
}
}
PlacesViewHolder.java
In this line "intent.putExtra(PlacesDetail.PLACES_NAME,);" How can I send name?
public class PlacesViewHolder extends RecyclerView.ViewHolder {
CardView cv;
public TextView name;
public TextView address;
public ImageView photo;
public PlacesViewHolder(final View itemView) {
super(itemView);
cv = (CardView)itemView.findViewById(R.id.cv);
name = (TextView)itemView.findViewById(R.id.person_name);
address = (TextView)itemView.findViewById(R.id.person_age);
photo = (ImageView)itemView.findViewById(R.id.person_photo);
itemView.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent intent = new Intent(context, PlacesDetail.class);
intent.putExtra(PlacesDetail.PLACES_NAME,);
context.startActivity(intent);
}
});
}
public TextView getAddress() {
return address;
}
public TextView getName() {
return name;
}
public ImageView getPhoto() {
return photo;
}
}
This is the complete example of custom Adapter where i'm able to get the details of particular items. In MainActivity you need to set the adapter :
adapter = new MyAdapter(getApplicationContext(), account_no, title, aFN1, aLN1,aFN2, aLN2,aFN3, aLN3,isavilable,waitlist,flag);
adapter.notifyDataSetChanged();
mRecyclerView.setAdapter(adapter);
Now see the code for the custom Adapter :
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
String TAG = "MyAdapter";
Context context;
private String[] accountNo;
private String[] title;
private String[] afn1;
private String[] aln1;
private String[] afn2;
private String[] aln2;
private String[] afn3;
private String[] aln3;
private String[] isAvailable;
private String[] waitlist;
private int flag;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView account_no,title,afn1,afn2,aln1,aln2,color,is_available;
private ImageView img_android;
CardView cardView;
public ViewHolder(CardView v) {
super(v);
account_no = (TextView)v.findViewById(R.id.acctno);
title = (TextView)v.findViewById(R.id.title);
afn1 = (TextView) v.findViewById(R.id.afn1);
cardView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(Context context, String[] accountNo,String[] title,String[] afn1,String[] aln1,String[] afn2,String[] aln2,String[] afn3,String[] aln3,String[] isAvailable, String[] waitlist,int flag) {
this.context = context;
this.accountNo = accountNo;
this.title = title;
this.afn1 = afn1;
this.aln1 = aln1;
this.afn2 = afn2;
this.aln2 = aln2;
this.afn3 = afn3;
this.aln3 = aln3;
this.isAvailable = isAvailable;
this.waitlist = waitlist;
this.flag = flag;
Log.d(TAG,afn1.toString() +aln1+afn2+aln2+afn3+aln3.toString()+waitlist);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
CardView cv = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item, parent, false);
return new ViewHolder(cv);
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final CardView cardView = holder.cardView;
final TextView accountno = (TextView)cardView.findViewById(R.id.acctno);
accountno.setText(accountNo[position]);
final TextView titletxt = (TextView)cardView.findViewById(R.id.title);
titletxt.setText(title[position]);
final TextView afn1txt = (TextView) cardView.findViewById(R.id.afn1);
afn1txt.setText(afn1[position]+" "+aln1[position]);
Log.d(TAG,waitlist[position]);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int id = getItemViewType(position);
SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.MYPREFERENCE,Context.MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(Constant.ACCOUNT,accountNo[position]);
edit.putString(Constant.TITLE,title[position]);
edit.putString(Constant.AFN1,afn1[position]);
edit.putString(Constant.ALN1,aln1[position]);
edit.putString(Constant.AFN2,afn2[position]);
edit.putString(Constant.ALN2,aln2[position]);
edit.putString(Constant.AFN3,afn3[position]);
edit.putString(Constant.ALN3,aln3[position]);
edit.putBoolean(Constant.IS_AVAILABLE, Boolean.parseBoolean(isAvailable[position].toUpperCase()));
edit.putString(Constant.WAITLIST,waitlist[position]);
Log.d("WaitingNo2 :",""+String.valueOf(waitlist[position]));
edit.commit();
Intent intent = new Intent(v.getContext(), DetailsActivity.class);
v.getContext().startActivity(intent);
}
});
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return accountNo.length;
}
}
After All that get the value from sharedPreferences in the Activity which is called on Card Click:
preferences = getSharedPreferences("myshared", Context.MODE_PRIVATE);
AccountNo = sharedPreferences.getString(Constant.ACCOUNT,null).toUpperCase();
title = sharedPreferences.getString(Constant.TITLE,null).toUpperCase();
afn1 = sharedPreferences.getString(Constant.AFN1,null).toUpperCase();
aln1 = sharedPreferences.getString(Constant.ALN1,null).toUpperCase();
afn2 = sharedPreferences.getString(Constant.AFN2,null).toUpperCase();
aln2 = sharedPreferences.getString(Constant.ALN2,null).toUpperCase();
afn3 = sharedPreferences.getString(Constant.AFN3,null).toUpperCase();
aln3 = sharedPreferences.getString(Constant.ALN3,null).toUpperCase();
isAvailable = sharedPreferences.getBoolean(Constant.IS_AVAILABLE,isAvailable);
waitlist = sharedPreferences.getString(Constant.WAITLIST,waitlist);
Now do whatever you want and enjoy the code.
You can achieve this by creating an interface inside your adapter for an itemclicklistener and then you can set onItemClickListener from your PlacesActivity.
Somewhere inside your PlacesAdapter you would need the following:
private onRecyclerViewItemClickListener mItemClickListener;
public void setOnItemClickListener(onRecyclerViewItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public interface onRecyclerViewItemClickListener {
void onItemClickListener(View view, int position, String places_name);
}
Then inside your ViewHolder (which I've added as an inner class inside my adapter), you would apply the listener to the components you'd like the user to click, like so:
class PlacesViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
PlacesViewHolder(View view) {
super(view);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClickListener(v, getAdapterPosition(), PlacesDetail.PLACES_NAME);
}
}
}
This example shows an onClickListener being applied to the view inside PlacesViewHolder.
recyclerView.setAdapter(adapter);// set adapter on recyclerview
adapter.notifyDataSetChanged();// Notify the adapter
adapter.setOnItemClickListener(new PlacesAdapter.onRecyclerViewItemClickListener() {
#Override
public void onItemClickListener(View view, int position, String places_name) {
//perform click logic here (places_name is passed)
}
});
To implement this code, you would setOnItemClickListener to your adapter inside PlacesActivity as shown above.
try this , it's work with me correctly
Create a new class and this code
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
public interface OnItemClickListener {
public void onItemClick(View view, int position);
public void onLongItemClick(View view, int position);
}
GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && mListener != null) {
mListener.onLongItemClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildAdapterPosition(childView));
return true;
}
return false;
}
#Override public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
#Override
public void onRequestDisallowInterceptTouchEvent (boolean disallowIntercept){}
}
And in your Activity add this to your adapter implementation
mRecyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(getActivity(), mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
// do something
}
}
}
#Override
public void onLongItemClick(View view, int position) {
// do whatever
}
})
);

Categories