提问人:Treektus 提问时间:10/28/2023 最后编辑:David WasserTreektus 更新时间:11/1/2023 访问量:18
在特定位置不正确地检测 TextView
Incorrect detection of TextViews at a specific position
问:
我想在我的应用中创建一个简单的迷你游戏,但我无法检测用户正在触摸哪个视图。
这个视频将最好地解释我的问题:https://www.youtube.com/shorts/x3TwS5MVh7o
我已经测试了一些东西,我发现对于全屏活动,它可以完美地工作,但是如果我不想全屏执行此活动,我该如何解决这个问题?
我通过添加以下代码使此活动全屏显示:
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
这是我的代码:
活动
public class GameDrawActivity extends AppCompatActivity {
public static Path path = new Path();
public static Paint paint_brush = new Paint();
static Rect outRect = new Rect();
static int[] location = new int[2];
static TextView[] views;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_draw);
ConstraintLayout cl_container = findViewById(R.id.cl_container);
int childNumber = cl_container.getChildCount();
views = new TextView[childNumber];
for(int i=0;i<childNumber;i++){
views[i] = (TextView) cl_container.getChildAt(i);
}
}
public static void findView(int x, int y){
for(View view : views){
if(isViewInBounds(view, x, y)){
view.setBackgroundColor(Color.GREEN);
return;
}
}
}
private static boolean isViewInBounds(View view, int x, int y){
view.getDrawingRect(outRect);
view.getLocationOnScreen(location);
outRect.offset(location[0], location[1]);
return outRect.contains(x, y);
}
}
显示
public class Display extends View {
public static ArrayList<Path> pathList = new ArrayList<>();
...
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
path.moveTo(x,y);
invalidate();
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(x,y);
pathList.add(path);
invalidate();
GameDrawActivity.findView((int)x,(int)y);
return true;
default:
return false;
}
}
@Override
protected void onDraw(Canvas canvas) {
for(int i=0;i<pathList.size();i++){
paint_brush.setColor(Color.BLACK);
canvas.drawPath(pathList.get(i), paint_brush);
}
}
}
答:
0赞
David Wasser
11/1/2023
#1
看起来您的 Y 坐标与状态栏的高度相差。因此,您需要将状态栏的高度考虑在计算中。您应该能够通过获取位置并使用其 Y 坐标来确定状态栏的高度。ConstraintLayout
评论
android-studio