如何在android应用程序的整个布局中移动自定义视图



我正试图通过使用比例x和y值在整个应用程序布局上移动一个自定义视图(一个小圆圈(。举个例子,我想把圆圈移到屏幕的正中间,所以我会发送(0.5f,0.5f(,然后把每个值分别乘以我当前的屏幕宽度和高度。但由于某种原因,圆圈最终出现在其他地方,比如(0.5,0.5(出现在屏幕的右下角,就好像我使用了错误和更大的分辨率值,但我没有,因为我甚至对设备分辨率进行了硬编码,以确保这不是问题所在。

以下是我的自定义视图当前实现:

class CirclePointer(context: Context, attrs: AttributeSet) :View(context, attrs){
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
canvas.apply {
this!!.drawCircle(x, y, 5f, mCirclePointerPaint)
}
}
private val mCirclePointerPaint = Paint().apply {
}
fun move(newX: Float, newY: Float){
x = newX * 1280// hardcoded width
y = newY * 720// hardcoded height
invalidate()
requestLayout()
}// end of move
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
}
}

我的活动xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/heading"
android:orientation="vertical">
<my.package.annotation_views.CirclePointer
android:id="@+id/circlePointer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>

我刚刚学会了如何实现我自己的自定义视图,所以我很确定我错过了什么。因此,任何帮助都将不胜感激。

我尝试过的

  • 将我的CirclePointer宽度和高度设置为match_parent,而不是wrap_content

观察

我正在使用Android Studio 3.2和macOS Mojave

提前谢谢。

将圆的x和y分别设置在屏幕宽度和高度的一半将不起作用,因为圆的x和y是圆的左上角,而不是圆心。解决方案是从x中减去一半宽度,从y中减去一半高度,例如:

int left = screenWidth / 2 - circleWidth / 2
int top = screenHeight / 2 - circleHeight / 2
yourCircle.setX(left);
yourCircle.setY(top);

最新更新