我正在接触Android应用程序以完成它但我在recyclerView中发现了问题,而且我不知道如何获取recyclerView的项目文本? (当我点击该项目时)
答案 0 :(得分:5)
首先,您需要创建一个侦听器,将视图和位置作为参数。它直接存在于listView中。为此你可以创建一个这样的类:
public class RecyclerClickListener implements RecyclerView.OnItemTouchListener {
private OnItemClickListener mListener;
GestureDetector mGestureDetector;
public interface OnItemClickListener {
void onItemClick(View view, int position);
}
public RecyclerClickListener(Context context, OnItemClickListener listener) {
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent e) {
return true;
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
View childView = view.findChildViewUnder(e.getX(), e.getY());
if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
mListener.onItemClick(childView, view.getChildLayoutPosition(childView));
return true;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
然后在你的活动中:
recyclerView.addOnItemTouchListener( // and the click is handled
new RecyclerClickListener(getActivity(), new RecyclerClickListener.OnItemClickListener() {
@Override public void onItemClick(View view, int position) {
Log.d("click item", String.valueOf(position));
TextView textView = (TextView) view.findViewById(R.id.YourTextViewID);
Log.d("test",textView.getText().toString());
}
}
}));