how can i filter Recycler View using SearchView
i try all the video tuturial but all of them get thier item Recycler View from a list
but i get my item from db and dont know how should i do this
this is my adapter Code
public class AthleteAdapter extends RecyclerView.Adapter<AthleteAdapter.AthleteHolder> {
private List<Athlete> athletes = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public AthleteHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemview = LayoutInflater.from(parent.getContext()).inflate(R.layout.athlete_item, parent, false);
return new AthleteHolder(itemview);
}
#Override
public void onBindViewHolder(#NonNull AthleteHolder holder, int position) {
Athlete currnetAthlete = athletes.get(position);
holder.textViewName.setText(currnetAthlete.getAthlete_name());
holder.textViewLastname.setText(currnetAthlete.getAthlete_lastname());
holder.textView_phonenumber.setText(currnetAthlete.getAthlete_phonenumber());
holder.textViewTime1.setText(String.valueOf(currnetAthlete.getSign_in_time()));
holder.textViewTime2.setText(String.valueOf(currnetAthlete.getCheck_tution_time()));
}
public void setAthletes(List<Athlete> athletes) {
this.athletes = athletes;
notifyDataSetChanged();
}
public Athlete getposition(int position) {
return athletes.get(position);
}
#Override
public int getItemCount() {
return athletes.size();
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
public interface OnItemClickListener {
void onItemClick(Athlete athlete);
}
class AthleteHolder extends RecyclerView.ViewHolder {
private TextView textViewName, textViewLastname, textView_phonenumber, textViewTime1, textViewTime2;
public AthleteHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name_main);
textViewLastname = itemView.findViewById(R.id.lastname_main);
textView_phonenumber = itemView.findViewById(R.id.textView_number);
textViewTime1 = itemView.findViewById(R.id.time1);
textViewTime2 = itemView.findViewById(R.id.time2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(athletes.get(position));
}
}
});
}
}
}
Step 1 : Get all data from db and give that list to Adapter
usersList = db.getAll();
adapter = new dataAdapter(getApplicationContext(), usersList);
adapter.setdatainterfacemethod(this);
Step 2 : get Text from Searchview
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
filter(s.toString());
}
return false;
}
});
Step 3 : compare searchview text and list text if exits then give list to adapter
public void filter(String text) {
List<Users> name = new ArrayList<>();
for (Users u : usersList) {
if (u.getNAME().toLowerCase().contains(text.toLowerCase())) {
name.add(u);
}
}
adapter.filterlist(name);
}
Step 4 :- change list and notify adapter (in adapter class)
public void filterlist(List<Users> name) {
this.usersList = name;
notifyDataSetChanged();
}
--------------------- Adapter class -----------------
public class dataAdapter extends RecyclerView.Adapter<dataAdapter.viewholder> {
public List<Users> usersList;
Context context;
dataInterface dataInterface;
public dataAdapter(Context context, List<Users> usersList) {
this.usersList = usersList;
this.context = context;
}
public void setdatainterfacemethod(dataInterface dataInterface) {
this.dataInterface = dataInterface;
}
#NonNull
#Override
public viewholder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.include_recycle_demo, viewGroup, false);
return new viewholder(view);
}
#Override
public void onBindViewHolder(#NonNull final viewholder viewholder, final int i) {
}
#Override
public int getItemCount() {
return usersList.size();
}
public void filterlist(List<Users> name) {
this.usersList = name;
notifyDataSetChanged();
}
public class viewholder extends RecyclerView.ViewHolder {
public viewholder(#NonNull View itemView) {
super(itemView);
}
}
}
Related
i have nested recycle view and i want to remove one item (inner recycle view) from the outer recycle view but my code clear all adapters in the inner recycle view so how can i delete or clear only one list adapter from inner recycle view and is their is a better way to make nested recycle view .....?
public class MainWorkingTimeAdapter extends RecyclerView.Adapter<MainWorkingTimeAdapter.MainWorkingTimeViewHolder> {
private ArrayList<String> list = new ArrayList();
OnItemListener pOnItemListener;
String DAY_TAG;
Context context ;
ArrayList<WorkingTime>workingTimes;
String TAG ="MainWorkingTimeAdapter";
#NonNull
#Override
public MainWorkingTimeViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
return new MainWorkingTimeViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.main_working_time_layout, parent, false), pOnItemListener);
}
#Override
public void onBindViewHolder(#NonNull MainWorkingTimeViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.adapter = new WorkingTimePreviewAdapter();
holder.adapter.setList(workingTimes,list.get(position).toLowerCase(Locale.ROOT));
}
holder.recyclerView.setAdapter(holder.adapter);
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
holder.switch_.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (pOnItemListener != null) {
pOnItemListener.switchClicked(isChecked,position);
}
if(!isChecked){
holder.adapter.clearList();
}
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public void setList(ArrayList<String> list,String dayTag,Context context, OnItemListener onItemListener) {
this.list = list;
this.context =context;
this.DAY_TAG =dayTag;
this.pOnItemListener = onItemListener;
notifyDataSetChanged();
}
public class MainWorkingTimeViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
OnItemListener onItemListener;
RecyclerView recyclerView ;
WorkingTimePreviewAdapter adapter ;
Button button;
Switch switch_ ;
TextView title ;
public MainWorkingTimeViewHolder(#NonNull View v, OnItemListener onItemListener) {
super(v);
recyclerView = v.findViewById(R.id.recycler_main_work_time);
button = v.findViewById(R.id.button_right_main_work_time);
title = v.findViewById(R.id.tv_title_main_work_time);
switch_ = v.findViewById(R.id.switch_day_preview);
adapter = new WorkingTimePreviewAdapter();
this.onItemListener = onItemListener;
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onItemListener.rightButtonClicked(getAdapterPosition(),list.get(getAdapterPosition()).toLowerCase(Locale.ROOT));
}
}
public void updateRecycler(ArrayList<WorkingTime> workingTimes,int pos){
this.workingTimes = workingTimes;
notifyItemChanged(pos);
}
public interface OnItemListener {
void rightButtonClicked(int pos,String day);
void switchClicked(boolean isChecked,int pos);
}
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;
}
}
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);
}
}
my recyclerview is great in scrolling but when it contains more than two items and click on last item or the one before it gives me the wrong position this is
and throws a NullPointerException this is my whole code from adapter to the listener.
my code :
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
ViewHolder.setHeadText(i.getHead());
ViewHolder.setScoreText(i.getContent());
}
#Override
public int getItemCount() {
return items.size();
}
}
class ViewHolder extends RecyclerView.ViewHolder {
private RecyclerViewOnTouchItemListener.ClickListener clickListener;
private static TextView headText, urlText;
private ConstraintLayout itemLayout;
public ViewHolder(View itemView) {
super(itemView);
headText = (TextView) itemView.findViewById(R.id.list_item_header);
urlText = (TextView) itemView.findViewById(R.id.list_item_content);
itemLayout = (ConstraintLayout) itemView.findViewById(R.id.item_list);
// itemLayout.setOnClickListener(this);
}
public static void setHeadText(String headText) {
ViewHolder.headText.setText(headText);
}
public static void setScoreText(String scoreText) {
ViewHolder.urlText.setText(scoreText);
}
public static String getHeadText(){return headText.getText().toString();}
public static String getUrlText(){return urlText.getText().toString();}
}
class RecyclerViewOnTouchItemListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerViewOnTouchItemListener(Context context, final RecyclerView recyclerView, final ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = 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 && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) { }
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) { }
interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
and this is the activity that holds the recyclerview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
listOfUrl.setAdapter(adapter);
adapter.notifyDataSetChanged();
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
listOfUrl.addOnItemTouchListener(
new RecyclerViewOnTouchItemListener(this, listOfUrl
, new RecyclerViewOnTouchItemListener.ClickListener() {
#Override
public void onClick(View view, int position) {
if (selectedItems.get(position))
setItemSelectedState(false, position, Color.WHITE);
else
setItemSelectedState(true, position, Color.LTGRAY);
}
#Override
public void onLongClick(View view, int position) {}
private void setItemSelectedState(boolean isSelected, int position, int color) {
try {
listOfUrl.getChildAt(position).setBackgroundColor(color);
selectedItems.add(position, isSelected);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
})
);
find.setOnClickListener(this);
cancel.setOnClickListener(this); }
any on can tell me what i did wrong.
Simple solution, create interface class:
public interface ListListener {
void onClick(int pos);
void onLongClick(int pos);
}
Adjust the content of your RecyclerViewAdapter class:
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
private ListListener listener;
private List<ItemView> items;
private Context context;
public ListAdapter(List<ItemView> items, Context context) {
this.items = items;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_style, parent, false);
return new ViewHolder(view);
}
public ItemView getItem(int pos) {
return items.get(pos);
}
public void setListener(ListListener listener) {
this.listener = listener;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
ItemView i = items.get(position);
holder.setHeadText(i.getHead());
holder.setScoreText(i.getContent());
holder.itemLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = holder.getAdapterPosition();
if (listener != null && pos != RecyclerView.NO_POSITION) {
listener.onClick(pos);
}
}
});
holder.itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
int pos = holder.getAdapterPosition();
if (pos != -1) {
if (listener != null) {
listener.onLongClick(getItem(pos));
}
}
return true;
}
});
}
And in your Activity class I edited some parts:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_url_list);
context = getApplicationContext();
database = new DatabaseHelper(context);
listOfUrl = (RecyclerView) findViewById(R.id.url_list);
find = (Button) findViewById(R.id.findBtn);
cancel = (Button) findViewById(R.id.cancelBtn);
makeItPopUp();
listOfUrl.setLayoutManager(new LinearLayoutManager(this));
listOfUrl.setHasFixedSize(true);
listOfUrl.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
adapter = new ListAdapter(fillList(), context);
adapter.setListener(new SelectCountryDialogListener() {
#Override
public void onClick(int pos) {
ItemView item = adapter.getItem(pos);
}
#Override
public void onLongClick(int pos) {
ItemView item = adapter.getItem(pos);
}
});
listOfUrl.setAdapter(adapter);
selectedItems = new ArrayList<Boolean>(Arrays.asList(new Boolean[listOfUrl.getAdapter().getItemCount()]));
Collections.fill(selectedItems, Boolean.FALSE);
find.setOnClickListener(this);
cancel.setOnClickListener(this);
}
I'm pretty sure, that now it is very easy for you. Just to implement the functionality in onClick and onLongClick methods.
i have a recyclerView with two sections regular and Favourites and for populating my RecyclerView i have List<Object> my object class :
public class Object {
String id,channelName;
boolean isFavorite;
}
now i want to put the values which have isfavorite == true to top of my recyclerView inside my Favourite section but i don't know where to start or exactly what to do ? do i have to sort the List<Object> with booleans ? if anybody can give me a little hint or guidance then it'll be so helpful for me,
please this image for better understanding ,
this is what i'm trying to get
i added the Section in my RecyclerView by SimpleSectionedRecyclerViewAdapter
class DataModal
{
public String title;
public boolean isFavourite;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isFavourite() {
return isFavourite;
}
public void setIsFavourite(boolean isFavourite) {
this.isFavourite = isFavourite;
}
}
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private List<DataModal> mData;
public void add(DataModal s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public SimpleViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.simple_text);
}
}
public SimpleAdapter(Context context, ArrayList<DataModal> data) {
mContext = context;
if (data != null)
mData = data;
else mData = new ArrayList<DataModal>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.simple_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
DataModal data = mData.get(position);
holder.title.setText(data.getTitle());
holder.title.setOnClickListener(new Listener(position,mData.get(position)));
}
class Listener implements View.OnClickListener
{
DataModal Data;
int position;
Listener(int position,DataModal Data)
{
this.Data = Data;
this.position = position;
}
#Override
public void onClick(View view) {
if(Data.isFavourite())
{
//mark the view as unfavorite
}
else{
//mark the view as favorite
}
Toast.makeText(mContext,"Position ="+position,Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return mData.size();
}
}
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.SimpleViewHolder> {
private final Context mContext;
private List<String> mData;
public void add(String s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
public final TextView title;
public SimpleViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.simple_text);
}
}
public SimpleAdapter(Context context, String[] data) {
mContext = context;
if (data != null)
mData = new ArrayList<String>(Arrays.asList(data));
else mData = new ArrayList<String>();
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(mContext).inflate(R.layout.simple_item, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
holder.title.setText(mData.get(position));
holder.title.setOnClickListener(new Listener(position,mData.get(position),false,favview));
}
class Listener implements View.OnClickListener
{
ImageView favoriteView;
int position;
Listener(int position,String Data,boolean isFavourite,ImageView favoriteView)
{
this.favoriteView = favoriteView;
this.position = position;
}
#Override
public void onClick(View view) {
if(isFavourite)
{
//mark the view as unfavorite
}
else{
//mark the view as favorite
}
Toast.makeText(mContext,"Position ="+position,Toast.LENGTH_SHORT).show();
}
}
#Override
public int getItemCount() {
return mData.size();
}
}