How to use button and recycleView together - java

I have a recycleView (see picture). You see there are 2 buttons too. Here's the layout file.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="80dp"
android:background="#color/white">
<de.hdodenhof.circleimageview.CircleImageView
android:layout_marginLeft="10dp"
android:id="#+id/main_picture"
android:layout_width="45dp"
android:layout_height="50dp"
android:src="#drawable/pfl_img"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_toRightOf="#id/main_picture"
android:layout_marginRight="5dp"
android:layout_marginLeft="10dp"
android:id="#+id/relativeLayout2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Edem Palonik"
android:textSize="17sp"
android:id="#+id/textName"
android:textColor="#color/black"
android:layout_above="#+id/textDescription"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profession and ..."
android:textColor="#color/black"
android:textSize="17sp"
android:id="#+id/textDescription"
android:layout_centerVertical="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="20dp"
android:layout_height="18dp"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:id="#+id/historyIcon"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/date"
android:textSize="14sp"
android:text="17/12/2017/13:46"
android:layout_marginTop="2dp"
android:layout_below="#+id/textDescription"
android:layout_toEndOf="#+id/historyIcon" />
</RelativeLayout>
<Button
android:id="#+id/call_button"
android:layout_width="32dp"
android:layout_height="32dp"
android:layout_marginRight="10dp"
android:background="#drawable/call_img"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/sms_button" />
<Button
android:id="#+id/sms_button"
android:layout_width="37dp"
android:layout_height="32dp"
android:background="#drawable/sms_img"
android:layout_alignTop="#+id/call_button"
android:layout_alignParentEnd="true" />
<View
android:layout_width="match_parent"
android:layout_height="0.8dp"
android:layout_alignParentBottom="true"
android:background="#color/gray" />
I know, I can use recyclerViewItemCLickListener, but I wanna click on last 2 buttons separately, so what do I need to do?
So I wanna click on last buttons separately, without clicking all line, I want only last buttons to be clickable.
Here's the java code.
public class ConnectionsFragment extends Fragment {
private View mainView;
private RecyclerView recyclerView;
private List<Connections_item> list;
private Button call, sms;
public ConnectionsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.connections_fragment, container, false);
recyclerView = (RecyclerView) mainView.findViewById(R.id.recycler_connection);
ConnectionsAdapter adapter = new ConnectionsAdapter(getActivity(), list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
init(mainView);
return mainView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<>();
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun1", "Inch vor text", R.drawable.missed, "23/11/1998 00:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun2", "Inch vor text", R.drawable.callagain, "24/11/1998 01:00"));
list.add(new Connections_item(R.drawable.pfl_img, "Anun Azganun3", "Inch vor text", R.drawable.missed, "25/11/1998 02:00"));
public void init(View v) {
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
// call.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
// }
// });
// sms.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Toast.makeText(getActivity(), "Whom you wanna send sms?", Toast.LENGTH_SHORT).show();
// }
// });
}
}
Here's the adapter code.
public class ConnectionsAdapter extends RecyclerView.Adapter<ConnectionsAdapter.MyViewHolder> {
Context context;
List<Connections_item> list = new ArrayList<>();
public ConnectionsAdapter(Context context, List<Connections_item> list) {
this.context = context;
this.list = list;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
v = LayoutInflater.from(context).inflate(R.layout.connections_view_item, parent, false);
MyViewHolder holder = new MyViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
}
#Override
public int getItemCount() {
return list.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView mainImage, historyImage;
TextView fullName, description, date;
Button call, sms;
public MyViewHolder(View v) {
super(v);
mainImage = (ImageView) v.findViewById(R.id.main_picture);
historyImage = (ImageView) v.findViewById(R.id.historyIcon);
fullName = (TextView) v.findViewById(R.id.textName);
description = (TextView) v.findViewById(R.id.textDescription);
date = (TextView) v.findViewById(R.id.date);
call = (Button) v.findViewById(R.id.call_button);
sms = (Button) v.findViewById(R.id.sms_button);
}
}
}

Using interface you can achieve this
public class TestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context mContext;
ArrayList<Data> mData;
OnButtonClickListeners onButtonClickListeners;
public TestAdapter(Context mContext, ArrayList<String> mData) {
this.mContext = mContext;
this.mData = mData;
}
public void setOnButtonClickListeners(OnButtonClickListeners listener){
this.onButtonClickListeners = listener;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
MyViewHolder vh;
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//Bind holder here
}
#Override
public int getItemCount() {
return mData.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
#Bind(R.id.call_button)
Button btnCall;
#Bind(R.id.sms_button)
Button btnSms;
public MyViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
btnCall.setOnClickListener(this);
btnSms.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(this.onButtonClickListeners!=null){
switch (v.getId()) {
case R.id.call_button:
onButtonClickListeners.onCallClick(getAdapterPosition());
break;
case R.id.sms_button:
onButtonClickListeners.onSmsClick(getAdapterPosition());
break;
}
}
}
}
public interface OnButtonClickListeners{
void onCallClick(int position);
void onSmsClick(int position);
}
}
Then After you can use the call to this interface from Activity and Fragment like below
private void setUpRecyclerView(){
mAdapter = new ProfileAdapter(mContext,new ArrayList<String>());
lm = new LinearLayoutManager(getActivity());
rvFeeds.setLayoutManager(lm);
rvFeeds.setAdapter(mAdapter);
mAdapter.setOnButtonClickListeners(new OnButtonClickListeners() {
#Override
public void onCallClick(int position) {
//To do your code here
}
#Override
public void onSmsClick(int position) {
//To do your code here
}
})
}

As adapter holds the recyclerView item and buttons are in the item
so all code related to button will be in the adapter only.
In adapter modify the code :
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.mainImage.setImageResource(list.get(position).getMainImage());
holder.fullName.setText(list.get(position).getFullName());
holder.description.setText(list.get(position).getDescription());
holder.historyImage.setImageResource(list.get(position).getHistoryIcon());
holder.date.setText(list.get(position).getDate());
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna call?", Toast.LENGTH_SHORT).show();
}
});
holder.sms.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getActivity(), "Whom you wanna send sms?", }
});
}
In java file just remove call and sms button initialization and listners.

You can try to implement onClickListener to the buttons when you are creating the view in the ViewHolder for the recycler view. Then pass an interface with two methods for two buttons and implement the interface in where ever you require.
Like the example:
public class MyViewHolder extends RecyclerView.ViewHolder {
public MyViewHolder(View itemView, ButtonClickListener listner) {
super(itemView);
Button b1 = itemView.findViewById(...);
Button b2 = itemView.findViewById(...);
b1.setOnClickListener(view -> listener.onButton1Click());
b2.setOnClickListener(view -> listener.onButton2Click());
}
}
And now the interface
public interface ButtonClickListener {
void onButton1Click();
void onButton2Click();
}
Otherwise, if you are accustomed with bus you can use instead of using interface. It will make the code much cleaner.

Related

Android RecyclerView - How to get items selected in Fragment class which calls CustomAdapter. I know how to use get(getAbsoluteAdapterPosition()

Below recycler view code is working fine and I can Toast message what recycler view position was selected in RecycleAdapter class. But I want to know how can I get what recycler position selected in HomeFragment class?. I tried to get position by setting onclick listener to Imageview and Textview but gives error as reference to Null. Basically I want to use get(getAbsoluteAdapterPosition() in HomeFragment class to know what item selected and navigate to another Fragment. get(getAbsoluteAdapterPosition() is working as expected inside RecycleAdapter.class
binding.recyclerview.setOnClickListener is not working in HomeFragment.class. no error but no when I click on recycler views this is not shooted.
txt.setOnClickListener is giving error as null refernce which makes sense. because this is inflated in Adapter class but trying to refer in HomeFragement class. So how can I get what selected in homefragment.class. Thanks in advance
HomeFragment.class
'''
public class HomeFragment extends Fragment {
HomeFragmentBinding binding;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.id.home_fragment, container, false);
return v;
}
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
%% some code here %%
recycleAdapter = new RecycleAdapter(list);
binding.recyclerview.setAdapter(recycleAdapter);
TextView txt = (TextView) binding.getRoot().findViewById(R.id.recycler_text);
txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "Clicked on Image", Toast.LENGTH_SHORT).show();
}
});
binding.recyclerview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "RecyclerView clicked", Toast.LENGTH_SHORT).show();
Log.d("RecyclerViewclicked", " --- ");
}
});
'''
RecycleAdapter.class
'''
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder>{
RecyclerRowItemsBinding binding;
List<IconsModel> iconsList;
public RecycleAdapter(List<IconsModel> iconslist) {
this.iconsList = iconslist;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflator = LayoutInflater.from(parent.getContext());
View v = inflator.inflate(R.layout.recycler_row_items, parent, false);
MyViewHolder myviewholder = new MyViewHolder(v);
return myviewholder;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
}
#Override
public int getItemCount() {
//return 20;
return iconsList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IconsModel iconModel = iconsList.get(getAbsoluteAdapterPosition());
Toast.makeText(***itemView.getContext(), "Clicked on "+iconModel.getIconName()***, Toast.LENGTH_SHORT).show();
}
});
}
}
;
}
'''
home_fragment.xml
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="1dp"
tools:layout_editor_absoluteY="1dp"
app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"/>
</androidx.constraintlayout.widget.ConstraintLayout>
'''
recycler_row.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_gravity="center"
android:layout_margin="5dp"
android:orientation="horizontal"
app:cardCornerRadius="5dp"
app:cardElevation="5dp"
app:cardBackgroundColor="#color/home_bg_cardview">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground"
android:backgroundTint="#color/home_bg_cardview"
android:weightSum="2">
<ImageView
android:id="#+id/recycler_image"
android:layout_width="0dp"
android:layout_height="120dp"
android:layout_weight="0.5"
app:srcCompat="?android:attr/actionModeWebSearchDrawable"
tools:ignore="ContentDescription" />
<TextView
android:id="#+id/recycler_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginBottom="29dp"
android:layout_weight="1.5"
android:gravity="center"
android:text="Browse Items"
android:textAlignment="center"
android:textSize="24sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
If you want to get the click event of recyclerview item in HomeFragment ,
Interface It's a good choice
//RecycleAdapter
private RecyclerViewListener recyclerViewListener
public void setRecyclerViewListener(RecyclerViewListener recyclerViewListener){
this.RecyclerViewListener recyclerViewListener ;
}
public Interface RecyclerViewListener{
void onClick(View view);
}
class MyViewHolder extends RecyclerView.ViewHolder{
ImageView imageView;
TextView recyclertext;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
recyclertext = itemView.findViewById(R.id.recycler_text);
recyclertext .setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recyclerViewListener !=null)recyclerViewListener.onClick(v)
}
});
}
//HomeFragment
recycleAdapter.setRecyclerViewListener(new RecyclerViewListener{
#Override
public void onClick(View v) {
//todo
}
})
Create Interface Class in your Project
public interface ItemClick {
public void onClick(IconsModel IconsModel,int pos);
}
Interface class call your recyclerAdapter
public class RecycleAdapter extends RecyclerView.Adapter<RecycleAdapter.MyViewHolder> {
Context context;
List<IconsModel> iconsList;
ItemClick click;
public TokensListAdapter(Context context, List<IconsModel> iconsList, ItemClick click) {
this.context = context;
this.tokensModelList = tokensModelList;
this.click = click;
}
#NonNull
#Override
public TokensListAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.R.layout.recycler_row_items,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull TokensListAdapter.ViewHolder holder, int position) {
IconsModel iconModel = iconsList.get(position);
holder.imageView.setImageResource(iconModel.getImageid());
holder.recyclertext.setText(iconModel.getIconName());
holder.itemView.setOnClickListener(v -> {
click.onClick(iconModel,position);
});
}
#Override
public int getItemCount() {
return iconsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView imageView;
TextView recyclertext;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.recycler_image);
recyclertext = itemView.findViewById(R.id.recycler_text);
}
}
}
Interface Class implement Your Fragment
public class HomeFragment extends Fragment implements ItemClick {
//adapter assign
recycleAdapter = new RecycleAdapter(getContext,list,this);
override method import your fragment
#Override
public void onClick(ItemCLick click, int pos) {
Toast.makeText(getContext(), "Clicked" + pos, Toast.LENGTH_SHORT).show();
}

NULL Pointer Exception Error Application Crashed After Clicking on Recycler List Item

I am working on an android application that is showing data in Recycle List View Holder. When I Click on List Item in Recycler View Holder the application crashes.
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
#Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UserRecyclerAdapterSavedUsers.class.getSimpleName(),""+listUsers.size());
return listUsers.size();
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
}
#Override
public void onClick(View v) {
if (itemClickListenerLongPressed != null) itemClickListenerLongPressed.onClick(v, getAdapterPosition());
Toast.makeText(mContext, "USMAN", Toast.LENGTH_SHORT).show();
}
}
}
Here is the users List activity
public class UsersListActivity extends AppCompatActivity implements ItemClickListenerLongPressed{
AppCompatActivity activity = UsersListActivity.this;
AppCompatTextView textViewName;
RecyclerView mRecyclerView;
AppCompatButton textViewButtonNewUser;
UserRecyclerAdapterSavedUsers userRecyclerAdapterSavedUsers;
List<User> listUsers;
DatabaseHelper databaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_record_updated_list);
mRecyclerView= (RecyclerView) findViewById(R.id.recyclerViewUsers);
mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
userRecyclerAdapterSavedUsers.setItemClickListenerLongPressed(this);
initViews();
initObjects();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(UsersListActivity.this,AdminMain.class));
finish();
}
#Override
protected void onRestart() {
super.onRestart();
}
/**
* This method is to initialize views
*/
private void initViews() {
textViewName = (AppCompatTextView) findViewById(R.id.textViewName);
textViewButtonNewUser = (AppCompatButton) findViewById(R.id.btnaddnew);
mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewUsers);
textViewButtonNewUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(UsersListActivity.this,UserRecordSaveActivity.class));
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initObjects() {
listUsers = new ArrayList<>();
userRecyclerAdapterSavedUsers = new UserRecyclerAdapterSavedUsers(listUsers);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(userRecyclerAdapterSavedUsers);
databaseHelper = new DatabaseHelper(activity);
String emailFromIntent = getIntent().getStringExtra("USERS");
textViewName.setText(emailFromIntent);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listUsers.clear();
listUsers.addAll(databaseHelper.getAllUser());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
userRecyclerAdapterSavedUsers.notifyDataSetChanged();
}
}.execute();
}
#Override
public void onClick(View view, int position) {
}
}
When I clicked on the List Item it crashed and the error was caused by Toast. As I remove the toast the Error goes because of using a try catch item not clicked.
Here is the image of Error.
After Removing try catch It again shows error but this time the error is shown on AlertDialog. Builder. Here is the image of error without try catch.
Image after removing try and catch
ERROR BEFORE REMOVING TOAST OVER ON CLICK
Image after adding toast logcat Error
Image After Adding Toast
The error is now on users list activity
Image after eidting of code
The actual data in list when removing the click listener
Actual data in list by removing the click listener
Here is my recycler layout file
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardCornerRadius="4dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/Indigo"
android:orientation="vertical"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="User ID"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="User ID"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Name"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Name"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="#string/hint_password"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="#string/hint_password"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="horizontal">
<android.support.v7.widget.AppCompatTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="Role"
android:textColor="#color/colorTextHint" />
<android.support.v7.widget.AppCompatTextView
android:id="#+id/textViewRole"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Role"
android:textColor="#android:color/darker_gray" />
</LinearLayout>
</LinearLayout>
Here is the Image of Logcat
Logcat Image at Updating Data
Here is the IMEIRecord Save activity Adapter like user record..
public class IMEIRecyclerAdapter extends RecyclerView.Adapter<IMEIRecyclerAdapter.ImeiViewHolder> {
private List<User> ListImei;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;
public IMEIRecyclerAdapter(List<User> ListImei) {
this.ListImei = ListImei;
}
#Override
public ImeiViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_imei, parent, false);
return new ImeiViewHolder(itemView);
}
#Override
public void onBindViewHolder(ImeiViewHolder holder, int position) {
final User user= ListImei.get(position);
holder.textViewImeiId.setText(ListImei.get(position).getImeiid());
holder.textViewImeiNo.setText(ListImei.get(position).getImei());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed) {
this.itemClickListenerLongPressed = itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
Log.v(UsersRecyclerAdapter.class.getSimpleName(),""+ListImei.size());
return ListImei.size();
}
public void displayingAlertDialogimei() {
final User user= new User();
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setTitle("Choose Option");
builder.setMessage("Update or Delete?");
builder.setPositiveButton("Update", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
goToUpdateActivity(user.getUserid());
dialog.cancel();
}
});
builder.setNeutralButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//go to update activity
dialog.cancel();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
private void goToUpdateActivity(String userid) {
Intent goToUpdate = new Intent(mContext, RoughUser.class);
goToUpdate.putExtra("USER_ID", userid);
mContext.startActivity(goToUpdate);
}
public class ImeiViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public AppCompatTextView textViewImeiId;
public AppCompatTextView textViewImeiNo;
LinearLayout layout;
public ImeiViewHolder(View view) {
super(view);
textViewImeiId = (AppCompatTextView) view.findViewById(R.id.textViewImeiId);
textViewImeiNo = (AppCompatTextView) view.findViewById(R.id.textViewImeiNo);
layout = (LinearLayout) view.findViewById(R.id.list_view_imei);
layout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
displayingAlertDialogimei();
}
}
}
first add id to your parent LinearLayout as, android:id="#+id/list_view"
and then update adapter class
public class UserRecyclerAdapterSavedUsers extends RecyclerView.Adapter<UserRecyclerAdapterSavedUsers.UserViewHolder> {
private List<User> listUsers;
Context mContext;
ItemClickListenerLongPressed itemClickListenerLongPressed;
View itemView;
public UserRecyclerAdapterSavedUsers(List<User> listUsers) {
this.listUsers = listUsers;
}
#Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_user_recycler_second, parent, false);
return new UserViewHolder(itemView);
}
#Override
public void onBindViewHolder(UserViewHolder holder, int position) {
holder.textViewID.setText(listUsers.get(position).getUserid());
holder.textViewName.setText(listUsers.get(position).getName());
holder.textViewPassword.setText(listUsers.get(position).getPassword());
holder.textViewRole.setText(listUsers.get(position).getRole());
}
public void setItemClickListenerLongPressed(ItemClickListenerLongPressed itemClickListenerLongPressed){
this.itemClickListenerLongPressed=itemClickListenerLongPressed;
}
#Override
public int getItemCount() {
return listUsers.size();
}
private void displayingAlertDialog() {
//displaying alert dialog box
AlertDialog.Builder builder = new AlertDialog.Builder(itemView.getContext());
builder.setMessage("your toast message here...");
builder.setCancelable(true);
builder.setPositiveButton(
"Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder.create();
alert11.show();
}
/**
* ViewHolder class
*/
public class UserViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//public AppCompatTextView ID;
public AppCompatTextView textViewID;
public AppCompatTextView textViewName;
public AppCompatTextView textViewPassword;
public AppCompatTextView textViewRole;
LinearLayout layout;
public UserViewHolder(View view) {
super(view);
textViewID = (AppCompatTextView) view.findViewById(R.id.textViewID);
textViewName = (AppCompatTextView) view.findViewById(R.id.textViewName);
textViewPassword = (AppCompatTextView) view.findViewById(R.id.textViewPassword);
textViewRole = (AppCompatTextView) view.findViewById(R.id.textViewRole);
layout = view.findViewById(R.id.list_view);
layout.setOnClickListener(this);
}
#Override
public void onClick(View v) {
displayingAlertDialog();
}
}
You have not declare mContext in your adapter class.
In Adapter class constructor may change like this.
public UserRecyclerAdapterSavedUsers(List<User> listUsers,Context context) {
this.mContext= context;
this.listUsers1 = listUsers;
user= new User();
}
and Recycle view Activity class you have to change
UserRecyclerAdapterSavedUsers myAdapter = new RecyclerViewAdapter(yourList,this);
Use the Recyclerview Item click like this click here
and then you can access the interface in your activity or fragment and then you can add whatever you need.
giving toast and populating AlertDialog inside the Adapteris not the proper way of coding

Firestore recycler adapter not fetching document names

I'm trying fetch all documents using FirestoreRecyclerAdapter here if there are 7 documents the RecyclerView items successfully populates with 7 items but here problem is the items which are having a text view are not getting populated with document names. Please take a look at my source code:
FriendsResponse Class:
#IgnoreExtraProperties
public class FriendsResponse {
FirebaseFirestore db;
public String getTable1() {
return Table1;
}
public void setTable1(String table1) {
Table1 = table1;
}
private String Table1;
public FriendsResponse() {
}
public FriendsResponse(String Table1) {
this.Table1 = Table1;
}
}
TableList Fragment where recyclerview is initialized:
public class TableListFragment extends Fragment{
private FirebaseFirestore db;
private FirestoreRecyclerAdapter adapter;
String documentnm;
RecyclerView recyclerView;
FloatingActionButton addt;
private StaggeredGridLayoutManager _sGridLayoutManager;
public static TableListFragment newInstance() {
TableListFragment fragment = new TableListFragment();
return fragment;
}
public TableListFragment() {
}
#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_tablelist, container, false);
recyclerView = view.findViewById(R.id.rectab);
addt=view.findViewById(R.id.addtab);
init();
getFriendList();
addt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return view;
}
private void init(){
_sGridLayoutManager = new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(_sGridLayoutManager);
db = FirebaseFirestore.getInstance();
}
private void getFriendList(){
Query query = db.collection("Order");
FirestoreRecyclerOptions<FriendsResponse> response = new FirestoreRecyclerOptions.Builder<FriendsResponse>()
.setQuery(query, FriendsResponse.class)
.build();
adapter = new FirestoreRecyclerAdapter<FriendsResponse, FriendsHolder>(response) {
#Override
public void onBindViewHolder(FriendsHolder holder, int position, FriendsResponse model) {
holder.exname.setText(model.getTable1());
holder.itemView.setOnClickListener(v -> {
Snackbar.make(recyclerView, model.getTable1(), Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
});
}
#Override
public FriendsHolder onCreateViewHolder(ViewGroup group, int i) {
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.list_item, group, false);
return new FriendsHolder(view);
}
#Override
public void onError(FirebaseFirestoreException e) {
Log.e("error", e.getMessage());
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
public class FriendsHolder extends RecyclerView.ViewHolder {
TextView exname;
public FriendsHolder(View itemView) {
super(itemView);
exname= itemView.findViewById(R.id.topicname);
}
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
}
}
This is the code of list_item:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView android:id="#+id/cardvw"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardCornerRadius="6dp"
card_view:cardElevation="3dp"
card_view:cardUseCompatPadding="true"
xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto">
<LinearLayout android:orientation="vertical" android:padding="5dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp">
<de.hdodenhof.circleimageview.CircleImageView
android:id="#+id/topiclogo"
android:layout_width="match_parent"
android:layout_gravity="center"
android:src="#drawable/table"
android:layout_height="wrap_content"
/>
<TextView android:textSize="15sp"
android:textStyle="bold"
android:textAlignment="center"
android:textColor="#ffffa200"
android:id="#+id/topicname"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</android.support.v7.widget.CardView>
As I understand, you want to set the id of the document to that TextView. So because those names are actually documents ids, you should use the following lines of code inside onBindViewHolder() method:
String id = getSnapshots().getSnapshot(position).getId();
holder.exname.setText(id);
The POJO class that you are using is useful when getting the properties of the documents, not to get the document ids.

How To Make a Phone Call with Button click in Recyclerview

i want use the method ACTION_CALL . the problem is when i click the button of the first cardview the app call the phone number 11111111 . & when i click the button of the second card view the app call also the same number 1111111.
what i want is when i click the button of the first cardview it call 111111
and when i click on the button of the second cardview it call 22222222
item layout xml :
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/tools"
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#android:color/transparent"
app:contentPaddingBottom="50dp"
android:paddingBottom="50dp"
card_view:cardElevation="6dp"
>
<RelativeLayout
android:longClickable="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="5dp"
android:paddingBottom="7dp">
<ImageView
android:id="#+id/profileImage"
android:layout_width="70dp"
android:layout_height="50dp"
app:civ_border_color="#7f89e9"
android:layout_marginLeft="5dp"
android:background="#drawable/contact1"
android:layout_alignTop="#+id/txtCelebName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_marginTop="8dp"
android:id="#+id/txtCelebName"
android:textSize="15dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/profileImage"
android:text="Large Text"
android:layout_marginLeft="18dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_marginLeft="18dp"
android:textSize="13dp"
android:id="#+id/txtCelebMovie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/txtCelebName"
android:layout_toRightOf="#+id/profileImage"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:layout_marginLeft="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="#+id/textView4"
android:layout_below="#+id/profileImage" />
<Button
android:background="#drawable/phonegreen"
android:layout_width="45dp"
android:layout_height="45dp"
android:id="#+id/buttonfordialog"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView5"
android:layout_toEndOf="#+id/textView5"
android:layout_marginLeft="22dp"
android:layout_marginStart="22dp" />
</RelativeLayout>
Adapter :
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemHolder> {
private List<Celebrity> celebrityList;
private final View.OnClickListener btnListener;
public ItemAdapter(List<Celebrity> celebrityList, View.OnClickListener btnListener) {
this.celebrityList = celebrityList;
this.btnListener = btnListener;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout, parent, false);
return new ItemHolder(itemView, btnListener);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
Celebrity item = celebrityList.get(position);
holder.txtCelebName.setText(item.getName());
holder.txtCelebMovie.setText(item.getFamousMovie());
}
#Override
public int getItemCount() {
return celebrityList.size();
}
public class ItemHolder extends RecyclerView.ViewHolder {
private Button buttoncalling;
public TextView txtCelebName, txtCelebMovie;
public ImageView profileImage;
public ItemHolder(View view, View.OnClickListener btnListener) {
super(view);
txtCelebName = (TextView) view.findViewById(R.id.txtCelebName);
txtCelebMovie = (TextView) view.findViewById(R.id.txtCelebMovie);
profileImage = (ImageView) view.findViewById(R.id.profileImage);
buttoncalling = (Button) view.findViewById(R.id.buttonfordialog);
buttoncalling.setOnClickListener(btnListener);
}
}
}
Main java :
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private ItemAdapter itemAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final View.OnClickListener btnListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
a_builder.setCancelable(false);
a_builder.setMessage("do you want to call this person!!!");
a_builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:11111111111"));
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startActivity(callIntent);
}
});
a_builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.setTitle("Alert !");
alert.show();
}
};
final Toolbar toolbar = (Toolbar)findViewById(R.id.MyToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout)findViewById(R.id.collapse_toolbar);
collapsingToolbarLayout.setTitle("Service/DPNG");
ArrayList<Celebrity> itemList = new ArrayList<>();
fillDummyData(itemList);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
itemAdapter = new ItemAdapter(itemList, btnListener);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemAdapter);
}
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setProfilePhotoLocation("http://ia.media-imdb.com/images/M/MV5BMTI3MDc4NzUyMV5BMl5BanBnXkFtZTcwMTQyMTc5MQ##._V1._SY209_CR13,0,140,209_.jpg");
celebList.add(celeb2);
This is pretty old but I hope someone may find this answer useful:
First of all, you're hard-coding the number to call in your button listener. Hence, whatever button you click on, you're asking it to make a call to 1111111.
What you need to do is to add a field in your Celebrity class for a phone number. Then in your adapter, create an interface that will be implemented in your MainActivity class. Thus, on click of an item (which in this case is a cardview), you retrieve the phone number of the celebrity, and feed that to your implemented interface where you make the call to the celebrity.
Doing so, you'll be retrieving the right phone number for each celebrity instead of using the hard-coded string you currently have.
Adapter:
public interface CardClickListener {
onCardClicked(Celebrity celebrity);
}
MainActivity:
public class MainActivity extends AppCompatActivity implements ItemAdapter.CardClickListener {
......
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
........
// add the following to your onCreate method
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(this, recyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Celebrity celebrity = itemList.get(position);
onCardClicked(celebrity);
}
#Override
public void onLongClick(View view, int position) {
}
}));
.........
}
// implement your interface here
#Override
public void onCardClicked(Celebrity celebrity) {
// don't forget to check for permissions
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + celebrity.phone));
}
......
// add phone numbers to your class definitions
private void fillDummyData(ArrayList<Celebrity> celebList) {
Celebrity celeb1 = new Celebrity();
celeb1.setName("Johny.D");
celeb1.setFamousMovie("Pirates ");
celeb1.setPhone("111111");
celeb1.setProfilePhotoLocation("#drawable/contact1");
celebList.add(celeb1);
Celebrity celeb2 = new Celebrity();
celeb2.setName("Arnold");
celeb2.setFamousMovie("The Terminator");
celeb2.setPhone("222222");
celeb2.setProfilePhotoLocation("http://ia.mediaimdb.com/images/M/209_.jpg");
celebList.add(celeb2);
}
} //mainactivity
RecyclerTouchListener:
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private ClickListener clickListener;
public RecyclerTouchListener(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) {
}
}
ClickListener:
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}

How to implement OnSetClickListener for button in RecyclerView?

I have been having difficulties making my device register button clicks within an android recyclerview and am not sure why it is not responding as I have looked around and it seems as though it should work. But what I really want to know is if I have put stuff in the wrong place, am I missing something and if so what?
Holder Class
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView time;
public ImageButton button;
public ViewHolder(View v) {
super(v);
time = (TextView)v.findViewById(R.id.time);
button = (ImageButton)v.findViewById(R.id.imageButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("Test", "Button clicked");
}
});
}
}
Adapter Class
public class ListAdapter extends RecyclerView.Adapter<ViewHolder> {
// WIll hold the timer objects passed through
ArrayList<Timer> lData = null;
// Provide a suitable constructor (depends on the kind of dataset)
public ListAdapter(ArrayList<Timer> myDataset) {
lData = myDataset;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_adapter, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.time.setText(lData.get(position).getTime());
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return lData.size();
}
// Gets the timers
public ArrayList<Timer> getData() {
return lData;
}
}
Main Activity Class (OnCreate Method)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new ListAdapter(timers);
mRecyclerView.setAdapter(mAdapter);
}
View Item
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip"
android:layout_margin="6dip"
android:background="?android:selectableItemBackground">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="fill_vertical"
android:textSize="28sp"
android:text="00:00:00"
android:paddingLeft="10dip"
android:layout_centerVertical="true"
android:layout_toEndOf="#+id/imageButton" />
<ImageButton
android:layout_width="50dip"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:src="#drawable/ic_action_pause"/>
</RelativeLayout>

Categories