I'm creating an adapter for a RecyclerView; currently creating an onClickListener to the items within the RecyclerView; I wish to go back to a fragment which I can't seem to do, so I have tried to add onBackPressed() with super.onBackPressed in the method as the fragment is on the previous page; I have called this in the onClickListener and it doesn't seem to work, any ideas how I can fix this?
Code is as follows:
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView text1, text2, text3;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
// This onClick doesn't accept onBackPressed() or popBackStack(), however I need to get this to the previous page which is a fragment.
}
});
You need to pass an OnClickListener (or a custom callback interface) to the Adapter and that you pass on to every ViewHolder. Once the viewholder onClick is called, you call the passed listener which then bubbles up to the Fragment/Activity where you created your Adapter.
A good sample of that can be found in this answer: https://stackoverflow.com/a/28304164/180538
And of course you can call onBackPressed() in this passed onClickListener or whatever code you want to have executed there
Related
The application has a BottomNavigationView for navigating between fragments. One of the Fragments related to the BottomNavigationView has a Fragment as a child containing a RecyclerView and each RecyclerView Item has a Button attached to it.
I would need to navigate the BottomNavigationView to another Fragment with an OnClick of the Button (Highlighted with the red) inside the RecyclerView Item. I have tried different ways but I have not gotten it to work so far.
The Click is handled inside the Adapter of the RecyclerView. (The code inside the OnClickListener is just to clarify what I am trying to do.)
#Override
public void onBindViewHolder(#NonNull LocationsViewHolder holder, int position) {
...
holder.showMarkerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomNavigationView navigation = (BottomNavigationView)v.findViewById(R.id.nav_view);
navigation.setSelectedItemId(R.id.navigation_map);
}
});
}
The easiest way is created an interface implemented by your Activity
First create an interface that i called OnItemClick :
public interface OnItemClick{
void onItemClick();
}
Following on your activity implement this interface like below :
public class MainActivity extends AppCompatActivity implements OnItemClick{
/*
rest of your code
*/
#Override
public void onItemClick() {
navigation.setSelectedItemId(R.id.navigation_map);
}
}
On your Fragment you need to pass the Activity into your Adapter
YourAdapter adapter = new YourAdapter(requireActivity());
And on your adapter you need to initialize the interface like below :
OnItemClick listener;
public YourAdapter(Activity activity) {
listener= ((MainActivity) activity);
}
And finaly to call the method on your activity just call it like below
#Override
public void onBindViewHolder(#NonNull LocationsViewHolder holder, int position) {
...
holder.showMarkerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listener.onItemClick();
}
});
}
I'm trying to implement a way to handle item selection on a RecyclerView. I personally don't like the way suggested in some answers on SO of passing through gestures, and I thought that implementing an OnClickListener, as suggested here and here, was waaay cleaner.
The fact is that... this pattern doesn't actually work! I'm really not able to understand why my OnClickListener.onClick is never called. It's kinda like another method intercepts the click before onClick can take care of it.
This is my code:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView tvName;
ImageView star;
public ViewHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.CHAT_ITEM_name);
star = (ImageView) itemView.findViewById(R.id.CHAT_ITEM_star);
Fonts.setTypeface(tvName, regular);
}
#Override
public void onClick(View view) {
int position = getLayoutPosition();
select(position);
}
}
Unfortunately it's very important for me to able to access the position of the clicked item in the whole dataset, in order to remove it, so doing something like indexOfChild isn't acceptable too: I tried, but this method gives you the position of the item in the visibile part of the list, thus making list.remove(position) impossible.
Looking at the updated code: you are not setting the onClickListener to any of the views in the ViewHolder. It is an understandable mistake to forget the click listener.
Just use:
tvName.setOnClickListener(this);
star.setOnClickListener(this);
You can set to both or just one of them. You can also simply get the parent layout of these two views, so that the whole item itself in the adapter can be clickable.
itemView.setOnClickListener(this);
You can do it in your onBindViewHolder
#Override
public void onBindViewHolder(ReportViewHolder holder, int position {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// handle your click here.
} });
}
Simplely Click Handler your ViewHolder. Recycler View don't have special attaching click handlers like ListView which has the method setOnItemClickListener().
** public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener
** in public ViewHolder(Context context, View itemView) set public void onClick(View view)
** get position by: int position = getLayoutPosition(); User user = users.get(position);
I am designing a RecyclerView list. Each item of the Recyclerview contains a LinearLayout. This LinearLayout contains two views, the first one is an EditText and the second one is Button. When user taps on the button, it fires an onclick event. From onClick listener, I need to get the content of the EditText. I don't find a way to access the content of a sibling view when the user taps on another sibling view.
My question is not "how can I set on click listener to a button inside adapter". Most of the people answered how to set onClick listener to a button which is there inside the recyclerview item. My question is bit different, when I am inside onClick method which is fired from button, how will I access the edittext which is a sibling of button. Every item has one edittext, so when I click on a button how will I find the correct edittext?
For example, I have a recylerview of size 10. And each item of recyclerview contains a LinearLayout and inside linearlayout two item, one is an Edittext and the other one is a Button. when I tap on 7th items button, how will I get the text of 7th item's Edittext? I hope I have explained it well
Any help would be appreciated.
First of, you need two references: one to your EditText and one to your Button. You can get those in your ViewHolder. Next, you need an OnClickListener. The ViewHolder can conveniently also implement one but you could also use onBindViewHolder() for that.
Inside that OnClickListener you can filter out your id with a switch statement if you want to and then get the content of the EditText like this:
switch(viewId) {
case R.id.buttonId:
String text = editText.getText().toString();
// do something with that text
return true;
}
In case you implemented an OnClickListener in your ViewHolder you can then do this button.setOnClickListener(this); inside your ViewHolder to make sure onClick() is actually called when you click the button.
EDIT:
Here's some sample code that should work for your case. I'm implementing View.OnClickListener here as mentioned above.
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
EditText editText;
Button button;
public ViewHolder(View itemView) {
super(itemView);
editText = itemView.findViewById(R.id.editText);
button = itemView.findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.button:
String text = editText.getText().toString();
break;
}
}
}
This is what it would look like if you were to do it in your onBindViewHolder() (in this case you would NOT implement the OnClickListener in your ViewHolder obviously):
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = holder.editText.getText().toString();
}
});
}
Step 1 :Make an abstract function in your adapter.
abstract void onButtonClicked(String text);
Step 2: Declare your adapter Abstract.
Step 3: Override the method (onButtonClicked(String text);) in your activity were you have instantiated the adapter.
Step 4: In your adapter inside the onClickListener for your button call the function :
onButtonClicked(editText.getText().toString());
and you'll get the string in your activity where you overrided the method.
You can use holder pattern for RecylcerView adapter. Then you can set click listener on your button and get the text from EditText.
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = simpleEditText.getText().toString()
}
});
}
}
You can do it inside your adapter which is being set on the recycler view.
public class MyViewHolder extends RecyclerView.ViewHolder {
public ImageView mImageView;
public MyViewHolder(View itemView) {
super(itemView);
mImageView = itemView.findViewById(R.id.imageView);
}
}
And in the bindview holder you can access the views
public void onBindViewHolder(#NonNull final ImageAdapter.MyViewHolder holder, int position) {
holder.mImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Your Code to access the edit text content
}
});
}
use a custom listener like this in the holder:
public class SimpleViewHolder extends RecyclerView.ViewHolder {
private EditText simpleEditText;
private Button simpleButton;
public SimpleViewHolder(final View itemView, final OnItemSelectedListener listener) {
super(itemView);
simpleEditText = (EditText) itemView.findViewById(R.id.simple_edit_text);
simpleButton = (Button) itemView.findViewById(R.id.simple_button);
simpleButton.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
String text = simpleEditText.getText().toString();
if(listener != null) listener.onItemSelected(text);
}
});
}
public interface OnItemSelectedListener{
void onItemSelected(String value);
}
}
Simply Use Your ViewHolder. It contains all the children you want. Implement the code inside your adapter where each item is inflated. Here is an example.
//inside the onBindViewHolder
viewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String text = viewHolder.editText.getText().toString();
Log.d("output", text);
}
});
If you are using FirebaseUI Implement this inside the populateViewHolder for older version and onBindViewHolder for the later versions.
People put -1 when they don't know the answer or when they do not understand question. So funny!! In onclick I took parent(getParent()) from the view and accessed the second child of the parent. With that I am able to access the content of the sibling.
` public void onClick(View v) {
for(int i = 0;i<parent.getChildCount();i++){
if(parent.getChildAt(i)instanceof EditText){
passwordView = (EditText)parent.getChildAt(i);
}
}
}`
I have a GridView in my activity. I am having 2 elements in the GridView. One is an ImageView and the other is a TextView.
I want to perform an action when clicking the ImageView only, but I want this to happen in the activity and not in the GridView adapter.
I handle the ImageView click in the getView() of my adapter, but I do not want it that way. I want to handle it in the activity when calling:
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this, items));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//THIS WORKS FINE
String string = ((TextView) v.findViewById(R.id.text)).getText().toString();
Log.d("string",string);
//THE PROBLEM OCCURS HERE
ImageView capture = (ImageView) v.findViewById(R.id.capture);
capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
});
//THE PROBLEM OCCURS HERE
The action is supposed to happen the first time I click the ImageView, but it only happens on the second click and further.
This is where I am stuck with the issue. I want this action to occur on the first click and not on the second click.
You can see the code block-
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String string = ((TextView) v.findViewById(R.id.text)).getText().toString();
Log.d("string",string);
//THE PROBLEM OCCURS HERE
ImageView capture = (ImageView) v.findViewById(R.id.capture);
capture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
Your imageview capture is adding any action after gridview is being clicked. So, after clicking first time it is executing and then setting click listener to imageview and then next click its executing its onClick block. So better, handle imageview click event inside adapter.
You can call method inside your activity from adapter class but you should implement setOnClickListener inside your adapter class.
with the help of interface, you can do that do one thing create an interface and implement it on your activity and get imageview click on the adapter and here initiate the interface and you will get the click inside the activity
I think the problem is that on the first click you just set OnClickListener on your imageView, and so its onClick() method is not getting called. On the second click though, as the listener is already set, onClick() is invoked.
Instead of setting new Listener to your imageView each time an item in the grid clicked (which does not make any sense by the way), you should do either of these:
If imageView in each item has to be handled the same way, set OnClickListener to the imageView in the adapter, when creating a view.
If not, pass the interface for handling imageView clicks to the constructor of the adapter, and then, in the activity, implement this interface when creating an adapter.
Create a method in you activity.
Now, in adapter, onClick call that method using
((Activityname)context).methodname(parameters);
I've got stuck with an issue about setting an OnItemClickListener to my RecyclerView items. I tried to set a listener the way described in the RecyclerView sample of Android Studio. So a listener is set in the ViewHolder class for my RecyclerView.
public class ProgramViewHolder extends RecyclerView.ViewHolder {
protected TextView vName;
protected ImageView vProgramImage;
public ProgramViewHolder(View v) {
super(v);
vName = (TextView) v.findViewById(R.id.programName);
vProgramImage = (ImageView) v.findViewById(R.id.programImage);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE PROBLEM !!
MainActivity.openSettings(1);
}
});
}
}
Now I want to call a method of my MainActivity openSettings(int ) to load a fragment:
public void openSettings(int layoutId) {
settingsFragment setFrag = new settingsFragment();
Bundle information = new Bundle();
information.putInt("layoutId", layoutId);
setFrag.setArguments(information);
getFragmentManager().beginTransaction()
.replace(R.id.fragmentContainer, setFrag)
.commit();
}
But now the problem. When I try to compile, it says "Non-static method 'openSettings(int )' cannot be referenced from a static context."
I quite not understand this error. Why is it a static context? The class ProgramViewHolder ist not declared static.
And the most important part: How can I fix it? I want to set a OnClickListener to every item of RecyclerView and call a public method of MainActivity.
Thanks a lot to you, for your time spending to help me.
It's not that ProgramViewHolder is static, it's because attempting to call your activity from a static context (you aren't calling a specific instance of the activity).
What you should do is pass the activity into your recyclerViewAdapter so that you have access to it.
For example
MainActivity mainActivity;
public CustomRecyclerViewAdapter(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
And to create the recyclerViewAdapter from MainActivity
CustomRecyclerView recyclerViewAdapter = new CustomRecyclerViewAdapter(this);
recyclerViewAdapter.setAdapter(recyclerViewAdapter);
You should then be able to access your method like this
mainActivity.openSettings(1);
Let me know if you have any trouble
//Edit
Here's how you would set onClick from bindViewHolder. You want to set up any onClickListeners here due to the way RecyclerView "recycles" data. For example, if each row should perform a different action on click, you need to make sure the click listener is tied to the specific row. Creating this in onBindViewHolder ensures this. If you want an entire row to be clickable, rather than elements inside, just create an outer view that fills the entire row. Then tie the onClickListener to that.
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
ProgramViewHolder programViewHolder = (ProgramViewHolder) holder;
programViewHolder.vName.setOnClicklistener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mainActivity.openSettings(1);
}
});
}
if you have context of the activity containing recyclerView, then you can simply do this:
your_view_holder.v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// HERE SOLUTION!!
((MainActivity)context).openSettings(1);
}
});
You can place this in onBindViewHolder(...)
How to get context:
Create another parameter of context in your Adapter's constructor , and pass the context from your activity once instantiating Adapter .
why pass the context:
i would recommend you to always pass context and assign it to any adapter's variable because this is something you would require every now and then while working with your adapter, so instead of using a workaround every time for context, just save it once .