我有一个布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="@android:color/black"
android:layout_height="match_parent">
<RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="@+id/progress_bar"
android:layout_centerInParent="true"
android:visibility="gone"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/long_press_container"
android:layout_centerInParent="true"
android:background="#40000000"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="match_parent">
</RelativeLayout>
我想在long_press_container相对布局中长按一个圆圈,但也要在触摸事件发生地点的回收网格视图中获取对象的引用。
public class CircleView extends View {
private float x;
private float y;
private int r;
// setup initial color
private final int paintColor = Color.WHITE;
// defines paint and canvas
private Paint drawPaint;
public CircleView(Context context, float x, float y, int r) {
super(context);
setupPaint();
this.x = x;
this.y = y;
this.r = r;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(x, y, r, drawPaint);
}
// Setup paint with color and stroke styles
private void setupPaint() {
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(3);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}}
我试过这个
mMyRecyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
Timber.e("recycler " + (motionEvent.getX()) + "," + (motionEvent.getY()));
mRelativeLayout.addView(new CircleView(getContext(), motionEvent.getX(), motionEvent.getY(), 25));
Timber.e("recycler " + view.getId());
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
mRelativeLayout.removeAllViews();
}
return false;
}
});
我绘制圆圈,但我无法获得列表视图中该坐标上的项目的引用。有没有办法从回收站视图或适配器获取该对象?
答案 0 :(得分:0)
在每个项目的回收者视图的viewHolder上设置触摸侦听器。这样您就可以获得用户触摸的回收者视图项。
答案 1 :(得分:0)
在here
的帮助下找到答案if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
mRelativeLayout.addView(new CircleView(getContext(), motionEvent.getX(), motionEvent.getY(), 25));
View v = mMyRecyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
Timber.d("position" + mMyRecyclerView.getChildAdapterPosition(v));
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
mRelativeLayout.removeAllViews();
}
在这里,您可以获得适配器中项目的位置,然后通过调用适配器列表并传递位置
来获取它