这是我的 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>
我创建了一个RecyclerView
与此XML文件的多个实例,因为他们是“项目”列表中。
我的onChangeClick
情况如下:
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);
}
我编程方式添加的情况下,item_simple_itemview
S到RecyclerView
,并更改文字simple_text
和btn
。当我点击个人项目的按钮按钮,不过,我得到的Toast通知Text: this is some temp text
。
如何使文本指的是项目,而不是基本的XML文件本身的具体情况?
android:onClick
,当你使用它,是古老的。你是我今天看到了,之后虽然没有见过它在使用多年的第二次。特别是,android:onClick
路由点击事件的方法,你在你的实现Activity
。这不是特别灵活。
而且,你的情况,如果你有N个按钮,每个按钮这N个按钮将调用相同的方法。而你得到的View
传递给你的方法作为参数,不一定是所有有助于识别您的哪一行RecyclerView
是被点击的一个。
我建议删除android:onClick
。相反,onBindViewHolder()
作为你工作的一部分,呼叫setOnItemClickListener()
上Button
。该OnClickListener
(或lambda表达式),您使用有可以参考的position
传入参数onBindViewHolder()
,如果您position
是final
。这样一来,你的点击处理程序必须直接访问position
,并从那里你可以在列表中找出特定项目position
对应。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句