gpt4 book ai didi

java - 如何从自定义 View android获取坐标

转载 作者:太空宇宙 更新时间:2023-11-04 11:57:39 25 4
gpt4 key购买 nike

我有一些带有 onTouchEvent 的自定义 View ,我在其中设置 mX 和 mY 。

mx=event.getX();
my=event.getY();

这是为了获取触摸事件的绘制路径 - 工作得很好,我可以查看在主 Activity 中定义的 TextView 中的坐标。

我想在我的主 Activity 布局中使用这两个属性用于设置背景颜色例如

if (mx > 1000 && my > 100 ){
set color
}

但似乎 mx 和 my 没有获得任何值我尝试的是

custom_view paintview = (custom_view) findViewById(R.id.custum_view_id)
float mx =paintview.getmx();
float my =paintview.getmy();

也许我没有在自定义 View 中正确定义 getmx ?

public float getmx(){
return mx;
}

我是 Java 和 Android 新手,所以请轻松一点:)

添加 MainActiviy。

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawing - custom view
drawView = (Drawing) findViewById(R.id.drawing);

findCoordinates();

TextView Coordinates = (TextView) findViewById(R.id.CNcoordinates);

//Coordinates - message with coordinates
paintView.setTextView(Coordinates);

}

private Drawing drawView;


public void findCoordinates() {
Drawing paintView = (Drawing) findViewById(R.id.drawing);
float xX = drawView.getmX();
float yY = drawView.getmY();
int nColor = Color.BLUE;
View buttonmove1 = findViewById(R.id.layoutMove);
if (Math.abs(xX) > 1000 && Math.abs(yY) > 1000) {
buttonmove1.setBackgroundColor(nColor);
}
}

坐标来自:

protected void onDraw(Canvas canvas) {
canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint);
canvas.drawPath(drawPath, drawPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {

mX = event.getX();
mY = event.getY();

View buttonmove = findViewById(R.id.drawing);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawPath.moveTo(mX, mY);

if(myCoordinates!=null){
myCoordinates.setText(":" + mX + " , " + ":" + mY);
}
break;




public void setTextView(TextView tv){
myCoordinates = tv;
}

最佳答案

完成 touchEvent 后使用接口(interface)或回调。你必须重新调用你的

findCoordinates()

因此它将更新您的 UI 以适应新值。

关于java - 如何从自定义 View android获取坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41209189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com