RecyclerView programmatically click - performClick - android

i'm searching function that programmatically click method. so i found some method. 'performClick()'
like that :
recyclerView.findViewHolderForAdapterPosition(position).itemView.performClick();
but it dosen't work in my case. I can't find solution. How do i use the performClick in Activity???
my Adapter - ViewHolder:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView virtNo;
private TextView score01;
private TextView score02;
private TextView score03;
private TextView totalScore;
private LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
this.virtNo = (TextView) itemView.findViewById(R.id.tv_virtNo);
this.score01 = (TextView) itemView.findViewById(R.id.tv_score01);
this.score02 = (TextView) itemView.findViewById(R.id.tv_score02);
this.score03 = (TextView) itemView.findViewById(R.id.tv_score03);
this.totalScore = (TextView) itemView.findViewById(R.id.tv_totalScore);
this.linearLayout = (LinearLayout) itemView.findViewById(R.id.ll_item_score);
virtNo.setOnClickListener(this);
score01.setOnClickListener(this);
score02.setOnClickListener(this);
score03.setOnClickListener(this);
score10.setOnClickListener(this);
}
#Override
public void onClick(View v) {
onClickListener.onClick(v, getAdapterPosition(), items.get(getAdapterPosition()));
}
}
public void setOnClickListener(OnClickListener<Score> onClickListener) {
this.onClickListener = onClickListener;
}
public interface OnClickListener<T> {
void onClick(View v, int position, T item);
}
my Adapter - onBindViewHolder
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Score item = items.get(position);
holder.virtNo.setText(item.virtNo);
holder.score01.setText(item.score01);
holder.score02.setText(item.score02);
holder.score03.setText(item.score03);
holder.totalScore.setText(itemSum(item));
}
}

I have tried to keep things easy to understand here, it is a complete example for listening to click event on individual items in RecyclerView, there are other ways to do it as well. This code works, You may modify it as it fits you, in case you have any question write them in comments. code is also available at GitHub
public class RecyclerViewOneActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycler_view_one);
initializeUI();
}
private void initializeUI() {
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.RecyclerViewOneActivity_RecyclerView);
RecyclerView.LayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
ArrayList<String> strings = new ArrayList<>();
strings.add("first");
strings.add("second");
MyAdapter adapter = new MyAdapter(getApplicationContext(), strings);
recyclerView.setAdapter(adapter);
}
private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private ArrayList<String> strings;
private LayoutInflater layoutInflater;
public MyAdapter(Context context, ArrayList<String> strings) {
this.context = context;
this.strings = strings;
layoutInflater = LayoutInflater.from(this.context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.single_item_recycler_view_one, parent, false);
MyViewHolder myViewHolder = new MyViewHolder(view);
return myViewHolder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final String text = this.strings.get(position);
holder.textView.setText("" + text);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, ""+text, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return strings.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
private LinearLayout linearLayout;
private TextView textView;
public MyViewHolder(View itemView) {
super(itemView);
linearLayout = (LinearLayout) itemView.findViewById(R.id.single_item_recycler_view_one_linear_layout);
textView = (TextView) itemView.findViewById(R.id.single_item_recycler_view_one_textView);
}
}
}
}
single_item_recycler_view_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:id="#+id/single_item_recycler_view_one_linear_layout"
android:orientation="vertical">
<TextView
android:id="#+id/single_item_recycler_view_one_textView"
android:layout_width="match_parent"
android:textColor="#000"
android:layout_height="wrap_content"
android:text="Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>

Related

How do I refresh the RecyclerView when an image is clicked?

I know this questions has been asked in the past. For some reason I can't seem to get it to work even though I tried using
understoodLanguageListAdapter.notifyDataSetChanged();
in my Activity file. Here is my code
Fragment file containing RecyclerView.
<android.support.v7.widget.RecyclerView
android:id="#+id/color_list"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Item layout:
<TextView
android:id="#+id/colorText"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/colorImage"
android:layout_height="wrap_content"
android:clickable="true"
android:visibility="visible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:srcCompat="#drawable/icn_close_bluepurple" />
Adapter code:
public class ColorsListAdapter extends RecyclerView.Adapter {
Context context;
List<String> list;
public ColorsListAdapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.colors_item,parent, false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(holder.textView.getText().toString());
}
});
}
#Override
public int getItemCount() {
return list.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
}
}
}
Activity code is as follows:
RecyclerView recyclerView;
List<String> list;
UnderstoodLanguageListAdapter understoodLanguageListAdapter;
---
---
#Override
protected void initialize(Bundle savedInstanceState) {
recyclerView = (RecyclerView) findViewById(R.id.color_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ColorsManager colorsManager = new ColorsManager();
list = colorsManager.getUnderstoodLanguageList();
colorsListAdapter = new ColorsListAdapter(this, list);
recyclerView.setAdapter(colorsListAdapter);
}
Any advice/tips about the fix is much appreciated.
Thank you!
You should change in adapter class like replace bellow code
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(holder.textView.getText().toString());
}
});
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
}
}
with new code
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
holder.textView.setText(list.get(position));
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView;
ImageView imageView;
public MyViewHolder(View itemView) {
super(itemView);
textView = (TextView) itemView.findViewById(R.id.colorText);
imageView = (ImageView) itemView.findViewById(R.id.colorImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int pos = getAdapterPosition();
ColorsManager colorsManager = new ColorsManager();
colorsManager.deleteFromColorsList(list.get(pos));
notifyItemRemoved(pos);
}
});
}
}
You should try notifyItemRemoved(position)
First of all you have to let adapter know that some changes has been made in certain position, to achieve that you need to use some callback (Listener), which has to be passed from your View -> Adapter -> ViewHolder or something similar.
You are creating new instance of ColorManager every time user clicks ImageView.
This new instance is obviously different from one that you used in initialize().
So, the item in new instance is updated and not the list that you passed to recycler adapter

RecyclerView is duplicating Alert Dialog results

I have a fragment that is suppose to display the results of my alert dialog in my RecyclerView. Every time I click the "ADD" in my dialog, it adds duplicated results to my RecyclerView. I've searched and searched but cannot seem to find what I am doing wrong. I've tried adding .clear(); but if I add that, nothing shows up in my RecyclerView at all. I've added in my adapter getItemId and getItemViewType to return position; but the items still get duplicated. I've added adapter.setData(model) followed by adapter.notifyDataSetChange(); and my RecyclerView still shows duplicated items. The app runs so I have no logcat to post. Thank you.
Model
public class SubjectsModel
{
//private long id;
private String mTitle;
private String mTeacher;
public String getmTitle()
{
return mTitle;
}
public void setmTitle(String title)
{
this.mTitle = title;
}
public String getmTeacher()
{
return mTeacher;
}
public void setmTeacher(String teacher)
{
this.mTeacher = teacher;
}
}
Fragment
public class SubjectsFrag extends DialogFragment implements
SubjectsEditor.OnAddSubjectListener
{
private static final String TAG = SubjectsFrag.class.getSimpleName();
#NonNull
Context context;
private EditText titleView, teacherView;
private String sTitle, sTeacher;
public EmptyRecyclerView recyclerView;
public RecyclerView.LayoutManager layoutManager;
public RecyclerSubAdapter recyclerSubAdapter;
public ArrayList<SubjectsModel> subMod = new ArrayList<>();
DbHelper helper;
#BindView(R.id.main_root)
ViewGroup root;
public SubjectsFrag() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_subjects, container, false);
FloatingActionButton fab = view.findViewById(R.id.fab_sub);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showDialog();
}
});
helper = new DbHelper(getActivity());
helper.getSubject();
titleView = view.findViewById(R.id.edit_subject);
teacherView = view.findViewById(R.id.edit_subject_teacher);
View emptyView = view.findViewById(R.id.empty_subject_view);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerSubAdapter = new RecyclerSubAdapter(getContext(), subMod);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(recyclerSubAdapter);
return view;
}
#Override
public void OnAddSubjectSubmit(String title, String teacher)
{
SubjectsModel model = new SubjectsModel();
model.setmTitle(title);
model.setmTeacher(teacher);
//subMod.clear();
subMod.add(model);
recyclerSubAdapter.setData(subMod);
recyclerSubAdapter.notifyDataSetChanged();
}
private void showDialog()
{
SubjectsEditor addSubjectDialog = new SubjectsEditor();
addSubjectDialog.setTargetFragment(this, 0);
addSubjectDialog.show(getFragmentManager(), null);
}
}
Adapter
public class RecyclerSubAdapter extends RecyclerView.Adapter<RecyclerSubAdapter.ViewHolder>
{
private static final String TAG = RecyclerSubAdapter.class.getSimpleName();
public List<SubjectsModel> subMod = new ArrayList<>();
private OnItemClicked onClick;
static ClickListener clickListener;
Context context;
DbHelper helper;
public RecyclerSubAdapter(Context context, ArrayList<SubjectsModel> subMod)
{
this.context = context;
this.subMod = subMod;
this.helper = new DbHelper(context);
}
#NonNull
#Override
public RecyclerSubAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.subjects_item_list, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final RecyclerSubAdapter.ViewHolder holder, final int position)
{
SubjectsModel currentSubject = subMod.get(position);
holder.titleView.setText(currentSubject.getmTitle());
holder.teacher.setText(currentSubject.getmTeacher());
//helper.addClass(subMod.get(position));
}
public class ViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener
{
TextView titleView;
TextView teacher;
CardView cardView;
public ViewHolder(View itemView)
{
super(itemView);
titleView = itemView.findViewById(R.id.subject_subject);
teacher = itemView.findViewById(R.id.subject_teacher_text);
cardView = itemView.findViewById(R.id.card_view);
}
#Override
public void onClick(View view)
{
if (clickListener != null)
{
}
}
}
#Override
public int getItemCount()
{
if (subMod == null)
{
Log.d(TAG, "sub is null");
}
return subMod.size();
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemViewType(int position)
{
return position;
}
public interface OnItemClicked
{
void onItemClick(int position);
}
public void setOnClick(OnItemClicked onClick)
{
this.onClick = onClick;
}
public void setClickListener(ClickListener clicked)
{
RecyclerSubAdapter.clickListener = clicked;
}
public interface ClickListener
{
void itemClicked(SubjectsModel model, int position);
}
public void setData(ArrayList<SubjectsModel> data)
{
this.subMod = data;
//this.subMod.clear();
this.subMod.addAll(data);
notifyDataSetChanged();
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main_root">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.example.ashleighwilson.schoolscheduler.adapter.EmptyRecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="60dp"/>
</LinearLayout>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true">
<TextView
android:id="#+id/empty_subject_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:visibility="gone"
android:text="#string/no_subjects"/>
</RelativeLayout>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_sub"
style="#style/FAB" />
</RelativeLayout>
In OnAddSubjectSubmit() you call subMod.add(model);
and then you call recyclerSubAdapter.setData(subMod); which in turn calls this.subMod.addAll(data);.
Check it yourself. I believe it's there where you add the new item twice.
Suggestion: comment out recyclerSubAdapter.setData(subMod); from OnAddSubjectSubmit().
this.subMod = data;
this.subMod.addAll(data);
You initilize subMod by assigning data to it, and later you add data again:
this.subMod.addAll(data);

How save the state of RecyclerView row item?

I have a recyclerview which populates data from SQL database. Now each row in the recyclerview has a seekbar which when moved displays it's progress in a textview inside the same row. The problem is when I scroll the recyclerview up or down then return back to the first changed row, the seekbar is returned to its default position. How can I make it save the new position ? In normal activities/fragments I use lifecycle methods as "onPause" to save/restore the state. Here we have onAttachedToRecyclerView, I think it should solve my problem but I don't know exactly how.
EDIT : here is a full simple app files which I'm working on to test this problem.
MainActivity.class
public class MainActivity extends AppCompatActivity {
private List<Score> scoreList = new ArrayList<>();
private RecyclerView recyclerView;
private MyAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
mAdapter = new MyAdapter(scoreList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
prepareScoreData();
}
private void prepareScoreData() {
Score score = new Score("title", 5);
scoreList.add(score);
for(int i= 0; i<1000; i++){
score = new Score("title", 5);
scoreList.add(score);
}
mAdapter.notifyDataSetChanged();
}
}
MyAdapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private List<Score> scoresList;
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView title, scoreView;
SeekBar seekbar;
public MyViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.title);
scoreView = (TextView) view.findViewById(R.id.score);
seekbar = (SeekBar) view.findViewById(R.id.seekbar);
}
}
public MyAdapter(List<Score> scoresList) {
this.scoresList = scoresList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
final Score score = scoresList.get(position);
holder.title.setText(score.getTitle());
if (!score.getProgressed()) {
holder.seekbar.setProgress(0) ;
} else {
holder.seekbar.setProgress(score.getSeekbarProgress());
}
holder.seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
holder.scoreView.setText(String.valueOf(i));
score.setSeekbarProgress(i);
score.setProgressed(true);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public int getItemCount() {
return scoresList.size();
}
}
Score class
public class Score {
private String title;
int seekbarProgress;
boolean progressed;
public Score() {
}
public Score(String title,int seekbarProgress) {
this.title = title;
this.seekbarProgress = seekbarProgress;
}
public void setProgressed(boolean progressed) {
this.progressed = progressed;
}
public void setTitle(String title) {
this.title = title;
}
public void setSeekbarProgress(int seekbarProgress) {
this.seekbarProgress = seekbarProgress;
}
public String getTitle() {
return title;
}
public int getSeekbarProgress() {
return seekbarProgress;
}
public boolean getProgressed() {
return progressed;
}
}
MainActivity_Layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.moaness.tut_recyclerview.MainActivity">
<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
android:id="#+id/my_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="60dp"
android:paddingBottom="60dp"
android:layout_marginBottom="10dp"
android:clickable="true"
android:background="#f2f2f2"
android:orientation="vertical">
<TextView
android:id="#+id/title"
android:text="title"
android:textColor="#color/title"
android:textSize="16dp"
android:paddingTop="16dp"
android:textStyle="bold"
android:layout_alignParentTop="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/score"
android:text="score"
android:layout_below="#+id/title"
android:textSize="16dp"
android:paddingBottom="16dp"
android:textStyle="bold"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/score"
android:id="#+id/seekbar"
/>
</RelativeLayout>
If you are using recyclerview you need to maintain states of each row, means if you are checking using a condition(i.e. if) at any stage of recyclerview item(in recyclerview adapter class) then you need to handle else as well. I can send you a code snippet so you can have a good idea for recyclerview adapter.
public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.ViewHolder> {
List<ViewHolder> holders = new ArrayList<ViewHolder>();
private ArrayList<ContactModel> arrayList = new ArrayList<>();
private Context context;
private LayoutInflater inflater;
public void clearAdapter() {
arrayList.clear();
notifyDataSetChanged();
}
public ContactsAdapter(Context context, ArrayList<ContactModel> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
public void setList(ArrayList<ContactModel> listSearch) {
this.arrayList = listSearch;
notifyItemRangeChanged(0, listSearch.size());
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.custom_row_for_contacts, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
holders.add(viewHolder);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final ContactModel current = this.arrayList.get(position);
holder.txtDriverName.setText(current.getName());
holder.txtDriverPhone.setText(current.getPhone());
if (current.getImgUrl().length() > 0) {
String urlLicenceThumb = UrlEndPoints.parentUrl + current.getImgUrl();
Glide.with(context).load(urlLicenceThumb).error(R.mipmap.ic_launcher).into(holder.imgDriver);
} else {
Glide.with(context).load(R.mipmap.ic_launcher).into(holder.imgDriver);
}
}
public void delete(int position) {
arrayList.remove(position);
notifyItemRemoved(position);
}
#Override
public int getItemCount() {
return (null != arrayList ? arrayList.size() : 0);
}
class ViewHolder extends RecyclerView.ViewHolder {
private TextView txtDriverName, txtDriverPhone;
private CircleImageView imgDriver;
private Button btnInvite;
private CheckBox chkAdd;
public ViewHolder(View itemView) {
super(itemView);
chkAdd = (CheckBox) itemView.findViewById(R.id.chkAdd);
imgDriver = (CircleImageView) itemView.findViewById(R.id.imgDriver);
txtDriverName = (TextView)itemView.findViewById(R.id.txtDriverName);
txtDriverPhone = (TextView) itemView.findViewById(R.id.txtDriverPhone);
btnInvite = (Button) itemView.findViewById(R.id.btnInvite);
}
}
}

Android - Recycler View onClick Listener not Working

I have made a RecyclerView adapter and using that adapter to inflate data in recycler view , I previously used the general Method of ListView onItemClickListner but it doesn't seems to work with RecyclerView , Plese anyone help me out with this
My RecyclerView Adapter class is :
public class TimeAdaptra extends
RecyclerView.Adapter<TimeAdaptra.RecyclerViewHolder> {
ArrayList<String> time, status;
public TimeAdaptra(ArrayList<String> title, ArrayList<String> dec) {
this.time = title;
this.status = dec;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.time_slice, parent, false);
RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(view);
return recyclerViewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.myTitle.setText(time.get(position));
holder.mydec.setText(status.get(position));
}
#Override
public int getItemCount() {
return time.size();
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView myTitle;
TextView mydec;
public RecyclerViewHolder(View view) {
super(view);
myTitle = (TextView) view.findViewById(R.id.timee);
mydec = (TextView) view.findViewById(R.id.status);
}
}
}
And I am doing inflation like this :
public class Slots extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.Adapter adapter;
RecyclerView.LayoutManager manager;
private ArrayList<String> Time = new ArrayList<String>();
private ArrayList<String> Status = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_slots);
Time.add("18:00");
Status.add("Available");
recyclerView = (RecyclerView) this.findViewById(R.id.timeslice);
manager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(manager);
recyclerView.setHasFixedSize(true);
adapter = new TimeAdaptra(Time, Status);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
Make the RecyclerViewHolder implement View.OnClickListener like this:
public static class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
TextView myTitle;
TextView mydec;
public RecyclerViewHolder(View view) {
super(view);
myTitle = (TextView) view.findViewById(R.id.timee);
mydec = (TextView) view.findViewById(R.id.status);
myTitle.setOnClickListener(this);
mydec.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.timee:
// do task
break;
case R.id.status:
//do task
break;
}
}
}
If you want to click on each item of the list then you should get the id of the root layout of the xml your are inflating and setOnClickListener() to it.

Android: RecyclerView onClick Listener is not getting

I have an array of 600 items. I list down all the array items in a RecyclerView and scrolling well.But when I try to access onClick listener it is not getting. I try to Implement View.OnClickListener and Override onClick.But its not working.
I want to Toast item in the list item when user click one of the row item in the view
Adapter code is
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private String mItem;
private TextView mTextView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
mTextView = (TextView) view.findViewById(R.id.item_title);
}
public void setItem(String item) {
mItem = item;
mTextView.setText(item);
}
#Override
public void onClick(View view) {
Log.d("TAG", "onClick " + getPosition() + " " + mItem);
}
}
private String[] mDataset;
public MyAdapter(String[] dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setItem(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
}
Can any one please help me
Thanks in advance :)
I have create a sample project using your code onClickListener working fine.Like when i click on item shows me the clicked item position in Log.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private MyAdapter mAdapter;
private RecyclerView mRecyclerView;
private String[] dataSet = {"Waleed", "Sarwar", "Yousuf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new MyAdapter(dataSet);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
</LinearLayout>
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private String[] mDataset;
public MyAdapter(String[] dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.setItem(mDataset[position]);
}
#Override
public int getItemCount() {
return mDataset.length;
}
public static class ViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener {
private String mItem;
private TextView mTextView;
public ViewHolder(View view) {
super(view);
view.setOnClickListener(this);
mTextView = (TextView) view.findViewById(R.id.item_title);
}
public void setItem(String item) {
mItem = item;
mTextView.setText(item);
}
#Override
public void onClick(View view) {
Log.d("TAG", "onClick " + getPosition() + " " + mItem);
}
}
}
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="56dp"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
if you are still facing the problem download the sample project from link below.
https://www.dropbox.com/s/xf3y8oxok0zlgxk/RecyclerViewOnClick.zip?dl=0
pls see jcobs ans it may help you
RecyclerView recyclerView = findViewById(R.id.recycler);
recyclerView.addOnItemTouchListener(
new RecyclerItemClickListener(context, new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
// do whatever
}
})
);
implement your code in onitemclick.
happy coding :)
You can handle it by setting on click listener to your parent view. Recyclerview don't provide you default item click listner same as listview.
So create object of your parent layout and set it click listner.
Your holder initialization.
class UserListHolder extends RecyclerView.ViewHolder {
RelativeLayout layoutMain;
UserListHolder(View itemView) {
layoutMain = (RelativeLayout)itemView.findViewById(R.id.layoutSquadItem);
}
}
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder,final int position) {
((UserListHolder)viewHolder).layoutMain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//handle click
}
});
}
You can also refer recycler view on click listner

Categories

Resources