This is my item_simple_itemview.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<TextView
android:id="@+id/simple_text"
android:layout_width="wrap_content"
android:layout_height="match_parent"
tools:text="Test"
android:text="This is some temp text" />
<Button
android:id="@+id/btn"
android:layout_width="208dp"
android:layout_height="50dp"
android:layout_marginTop="16dp"
android:minWidth="10dip"
android:minHeight="10dip"
android:onClick="onChangeClick" />
</LinearLayout>
I've created a RecyclerView
with multiple instances of this xml file, as they are "items" in the list.
My onChangeClick
is as follows:
public void onChangeClick(View view) {
View inflatedView = getLayoutInflater().inflate(R.layout.item_simple_itemview, null);
TextView textView = inflatedView.findViewById(R.id.simple_text);
Toast.makeText(getApplicationContext(), (CharSequence) ("Text: " + textView.getText()),
Toast.LENGTH_SHORT);
}
I programatically add instances of item_simple_itemview
s to the RecyclerView
, and change the text in simple_text
and btn
. When I click the button on an individual item's button, though, I get the Toast notification Text: this is some temp text
.
How do I make the text refer to that specific instance of the item and not the base xml file itself?
android:onClick
, as you are using it, is ancient. Yours is the second time that I have seen it today, after having not seen it used in years.
In particular, android:onClick
routes the click event to a method that you implement on your Activity
. That is not particularly flexible.
And, in your case, if you have N buttons, each of those N buttons will call the same method. While you get the View
passed into your method as a parameter, that isn't necessarily all that helpful for identifying which row in your RecyclerView
is the one that was clicked.
I recommend removing android:onClick
. Instead, in onBindViewHolder()
, as part of your work, call setOnItemClickListener()
on the Button
. The OnClickListener
(or lambda expression) that you use there can refer to the position
parameter passed into onBindViewHolder()
, if you make position
be final
. That way, your click handler has direct access to the position
, and from there you can find out what particular item in the list that position
corresponds to.