How to Open New Activity when Recycler Items Are Clicked - android

When I click item of RecyclerView and I want to be able to open another activity. How can I do this?
This code is my recycler adapter onBindViewHolder code.
#Override
public void onBindViewHolder(ViewHolder holder, int position)
{
holder.setItemclickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
if(isLongClick){
Toast.makeText(context,"Long Click"+ dataset.get(position),Toast.LENGTH_SHORT).show();
}
else{
Intent intent=new Intent(context,MainActivity.class);
startActivity(intent);
Toast.makeText(context,"short Click"+ dataset.get(position),Toast.LENGTH_SHORT).show();
}
}`enter code here`
});
Groups tiklanilan=dataset.get(position);
holder.groupnametext.setText(tiklanilan.getGroupname());
//holder.groupimage.setImageResource(tiklanilan.getImageURL());
}

You should not use setItemClickListener but instead in your onBindViewHolder add a clickListener on your root view and call the method startActivity in that clickListener.
#Override
public void onBindViewHolder(AccountListViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(yourIntent);
}
});
}

Related

Item position not updating in onBind method

I am implementing interface to detect when view is clicked in recycler view. I am removing the item when button is clicked. It works fine when once button is clicked. But when I click second time it removes the view present next to it.
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
optionsClickEvent.onDeleteClicked(position, imagePath);
showToast(String.valueOf(position));
}
});
}
Above code is executing in onBind. Next I am removing:
#Override
public void onDeleteClicked(int position, ArrayList<String> filePath) {
filePath.remove(position);
imageAdapter.notifyItemRemoved(position);
}
This works one time perfect. But items are not updated. And when I click delete button second time the item is removed at position+1.
User holder.getAdapterPosition() instead of layout position in onClick
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
optionsClickEvent.onDeleteClicked(holder.getAdapterPosition(), imagePath);
showToast(String.valueOf(position));
}
});
}

Attach click listener to each component of recycler view items [duplicate]

This question already has answers here:
Why doesn't RecyclerView have onItemClickListener()?
(31 answers)
RecyclerView onClick
(49 answers)
Closed 3 years ago.
I am learning Android Development. Struggling with this issue since 24 hours, need help.
On my each recycle view item I've two views ePaper & Website. I want to attach different on click listeners on the entire item, ePaper view and website view
In the above image, I need to put 3 click listeners
1. Click on red block 1 - do X (Intent to another activity)
2. Click on red block 2 - do Y (Intent to another activity)
3. Click on green block, entire item view - do Z (Dialog)
Tried many solutions. But, when I click red block, the listener in green block also comes to action in addition to listener in red block.
In the MainActivity
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(),
recyclerView, new ClickListener() {
String userid = Utils.getUserId(getApplicationContext());
#Override
public void onClick(View view, final int position) {
// Set listeners here for complete card view
final NewsPapersDataModel currentPaper = newsPapersList.get(position);
Log.d("TAG","Clicked 1");
newsSelectionDialog(currentPaper.getEpaper(),currentPaper.getWebsite());
}
#Override
public void onLongClick(View view, int position) {
Toast.makeText(MainActivity.this, "Long press on position :" + position, Toast.LENGTH_LONG).show();
}
}));
In the NewsPaperAdapter
public void onBindViewHolder(#NonNull final CustomViewHolder holder, int position) {
// Log.d("TAG","Holder is "+newsList);
final NewsPapersDataModel currentItem = newsList.get(position);
final String ePaperUrl = currentItem.getEpaper();
final String webSiteUrl = currentItem.getWebsite();
final String paperName = currentItem.getName();
holder.paperNameView.setText(newsList.get(position).getName());
if (TextUtils.isEmpty(currentItem.getEpaper())) {
// Log.d("TAGG","ePaper - "+currentItem.getEpaper()+" Website - "+currentItem.getWebsite());
holder.ePaperView.setVisibility(View.GONE);
} else if (TextUtils.isEmpty(currentItem.getWebsite())) {
holder.websiteView.setVisibility(View.GONE);
}
holder.ePaperView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveLinksToDb(userid, "ePaper", ePaperUrl);
Intent intent = new Intent(context, NewsAdvancedWebViewActivity.class);
intent.putExtra("url", ePaperUrl);
context.startActivity(intent);
}
});
holder.websiteView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveLinksToDb(userid, "Website", webSiteUrl);
Intent intent = new Intent(context, NewsAdvancedWebViewActivity.class);
intent.putExtra("url", webSiteUrl);
intent.putExtra("paperName",paperName);
context.startActivity(intent);
}
});
}
Please help me.
You need to create an interface in your adapter for click listeners and add onclick methods for every item you want.
Please look into the code below.
In your adapter, create interface
public interface OnClickListener {
void onPaperViewClick(View view, int position);
void onWebsiteViewClick(View view, int position);
}
And create method to set click listener from activity
public void setOnClickListener(OnClickListener listener) {
this.onClickListener= listener;
}
And in your onBindViewHolder method,
holder.ePaperView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickListener.onPaperViewClick(view, position);
});
holder.websiteView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onClickListener.onWebsiteViewClick(view, position);
});
and lastly, in your activity, set
recyclerViewAdapter.setOnClickListener(new NewsPaperAdapter.OnClickListener(){
#override
void onPaperViewClick(View view, int position){
// code to handle paper click
}
#override
void onPaperViewClick(View view, int position){
// code to handle website click
}
};
Remove your TouchListener from MainActivity and add ClickListener/ LonCkickListener inside your adapter.
onBindViewHolder(){
//rest of your code
holder.itemView.setOnClickListener(new OnClickListener{
#Override
public void onClick(View view) {
// Click implementation here
}
#Override
public void onLongClick(View view) {
// Long click implementation here
}
})
}
And inside your CustomViewHolder:
public class CustomViewHolder extends RecyclerView.ViewHolder{
// Other fields
View itemView;
public CustomViewHolder(View view){
// rest of initialization
itemView = view;
}
}
EDIT (OP wants to handle application logic inside Activity)
Create an interface class named RecyclerViewActionListener:
public interface RecyclerViewActionListener {
void onViewClicked(int clickedViewId, int clickedItemPosition);
void onViewLongClicked(int clickedViewId, int clickedItemPosition);
}
Then modify your RecyclerViewAdpater to have an additional field in constructor. We will pass listener from Activity to this adpater when we create Adapter:
public class RecyclerViewAdpater extends RecyclerView.Adapter<RecyclerViewAdpater.CustomViewHolder>{
private RecyclerViewActionListener mListener;
public RecyclerViewAdpater(ArrayList<Object> yourData,RecyclerViewActionListener mListener) {
this.mListener = mListener;
}
#NonNull
#Override
public CustomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false );
final CustomViewHolder holder = new CustomViewHolder(view);
holder.webView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onViewClicked(view.getId(), holder.getAdapterPosition());
}
});
holder.paperView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onViewClicked(view.getId(), holder.getAdapterPosition());
}
});
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.onViewClicked(view.getId(), holder.getAdapterPosition());
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
mListener.onViewLongClicked(view.getId(), holder.getAdapterPosition());
return false;
}
});
return holder;
}
public class CustomViewHolder extends RecyclerView.ViewHolder{
// Other fields
View itemView;
View webView;
View paperView;
public CustomViewHolder(View view){
super(view);
// rest of initialization
itemView = view;
}
}
}
And then implement RecyclerViewActionListener in your Activity and override methods from RecyclerViewActionListener:
public class MainActivity extends AppCompatActivity implements RecyclerViewActionListener {
RecyclerViewAdpater adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
// Skipped for the sake of brevity
// Pass your listener to adapter here
adapter = new RecyclerViewAdpater(yourData, this );
}
#Override
public void onViewClicked(int clickedViewId, int clickedItemPosition) {
switch (clickedItemPosition){
case R.id.web_view:
// Application logic when webview clicked
break;
case R.id.paper_view:
// Application logic when paperview clicked
break;
case R.id.recyclerview_item:
// Application logic when whole item clicked
break;
}
}
#Override
public void onViewLongClicked(int clickedViewId, int clickedItemPosition) {
switch (clickedViewId){
case R.id.recyclerview_item:
// Application logic when whole item long-clicked
break;
}
}
}
And in your xml file don't forget to assign ID to you views. Because we're detecting clicked view with their IDs.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recyclerview_item"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/web_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"/>
<ImageView
android:id="#+id/paper_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
try in your NewsPaperAdapter class onClickListner to parent layout of adapter like below
holder.parentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final NewsPapersDataModel currentPaper = newsPapersList.get(position);
Log.d("TAG","Clicked 1");
newsSelectionDialog(currentPaper.getEpaper(),currentPaper.getWebsite());
}
});
here parentLayout is your adapter item layout root view like Relative/Linear Layout

Onclick for each button inside RecyclerView items

How to get the position for clicked button inside the RecyclerView items
Here's my onBindViewHolder :
public void onBindViewHolder(MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
//if you need position, just use recycleViewHolder.getAdapterPosition();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});
}
If you need in onBindViewHolder only then you can use
holder.getAdapterPosition();
and if you need this position clicked in activity and fragment then you have to use callbacks from holder to activity and fragment and have to pass the same getAdapterPosition();
Edit: Added sample code for listening position click in fragment/activity
step 1: make an interface or callback
public interface RecyclerViewClickListener {
void onClick(View view, int position);
}
step 2: While initializing adapter class in fragment or activity pass the above-created reference as a parameter
public YourAdapter(List<SomeModel> modelList, RecyclerViewClickListener listener){
this.clickListener = listener;
}
step 3: In your ViewHolder or similar Class for view initialization do something like this
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private Button mapBtn;
ViewHolder(View v, RecyclerViewClickListener listener) {
super(v);
mapBtn = findViewById(R.id.mapBtn);
mListener = listener;
mapBtn.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mListener.onClick(view, getAdapterPosition());
}
}
you will get the position in your fragment or activity where you have passed the callback reference while initializing the adapter.
Use holder.getAdapterPosition();
public void onBindViewHolder(final MyViewHolder holder, int position) {
Masar masar=masrList.get(position);
holder.masarName.setText(masar.getMasarTitle());
holder.masarDesc.setText(masar.getMasarDescreption());
//How to get the Position
holder.masarImg.setImageResource(masar.getMasarImg());
holder.mapBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v ) {
Toast.makeText(getContext(), "The position is: "+holder.getAdapterPosition(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(v.getContext(), MapsActivity.class);
mContext.startActivity(intent);
}
});}

how can refresh list when click button in item listview

i have recyclerview and button on the all item of list. when i click the button in my adapter item deleted and i want refresh recycler and show new data.
#Override
public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
lietner = lietners.get(position);
holder.txt_en.setText(lietner.getText_en());
holder.txt_pe.setText(lietner.getText_pe());
holder.time.setText(lietner.getTime());
holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
holder.next_level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());
}
});
}
For re-initializing the recycler view and get callback on onBindViewHolder
simple call notifyDataSetChanged();
#Override
public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
lietner = lietners.get(position);
holder.next_level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// delete the item, or change the data.
notifyDataSetChanged();
}
});
}
i do this and it work for me!
#Override
public void onBindViewHolder(final LietnerViewHolder holder, final int position) {
lietner = lietners.get(position);
holder.txt_en.setText(lietner.getText_en());
holder.txt_pe.setText(lietner.getText_pe());
holder.time.setText(lietner.getTime());
holder.data.setText(HelperCalendar.g2j(lietner.getTime_create()));
holder.next_level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
G.databaseOpenHelper.goToNextLevel(lietners.get(position).getId());
lietners.remove(position);
notifyDataSetChanged();
}
});
}

Select all checkboxes in RecyclerView

How can I select all checkboxes in recyclerView?
I try to do it like this:
in Adapter:
public void selectAll(){
Log.e("onClickSelectAll","yes");
isSelectedAll=true;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
PersonDTO item = dataSet.get(position);
holder.tvName.setText(item.getName());
if (!isSelectedAll) holder.cbSelect.setSelected(false);
else holder.cbSelect.setSelected(true);}
In layout Activity I have a button with onClickListener:
private void onClickSelectAll(View view) {
getSelectPersonsAdapter().selectAll();
}
You made a simple mistake here
if (!isSelectedAll) holder.select_item.setChecked(false);
else holder.select_item.setChecked(true);
change setSelected into setChecked thats it
for both Select All and Unselect All
activty
checkall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(checkall.isChecked()){
categoryAdapter.selectAll();
}
else {
categoryAdapter.unselectall();
}
}
});
in adapter
public void selectAll(){
isSelectedAll=true;
notifyDataSetChanged();
}
public void unselectall(){
isSelectedAll=false;
notifyDataSetChanged();
}
#Override
public void onBindViewHolder(#NonNull final MyviewHolder holder, int position) {
final CategoryListItems list = categoryListItems.get(position);
holder.text.setText(list.getName());
if (!isSelectedAll){
holder.checkbox.setChecked(false);
}
else holder.checkbox.setChecked(true);
Select all Checkbox in recycler view with data binding
In adapter assign globally boolean parameter
public boolean isAllChecked = false;
Create select all method
public void setAllChecked(boolean isAllChecked) {
this.isAllChecked = isAllChecked;
notifyDataSetChanged();
}
In onBind view to write here
if (!isAllChecked) holder.ulbCheckboxBinding.chkBoxUlbName.setChecked(false);
else holder.ulbCheckboxBinding.chkBoxUlbName.setChecked(true);
Go to your activity and used onclick listener
binding.checkSelectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
adapter.setAllChecked(binding.checkSelectAll.isChecked());
adapter.notifyDataSetChanged();
}
});
thank you
#android

Categories

Resources