如何将数据从MainActivity传递到类扩展了View

时间:2019-01-17 16:08:19

标签: android android-canvas

我需要将xPos, yPos的{​​{1}}数据传递给MainActivity类,以便每次更改MyView时都画一个圆圈。

这是我的xPos, yPos的一部分:

MainActivity

if (!array.isEmpty()) { xPos = new String(); yPos = new String(); myView = new MyView(context); minIndex = array.indexOf(Collections.min(array)); xPos = checkXarray.get(array2.get(minIndex)); yPos = checkYarray.get(array2.get(minIndex)); } 类:

MyView

public class MyView extends View { public MyView(Context context) { super(context); } int x = 800; int y = 1200; int radius = 20; Paint paint; public void setXY(String xPos, String yPos){ this.x = Integer.parseInt(xPos); this.y = Integer.parseInt(yPos); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(Color.RED); canvas.drawCircle(x,y, radius, paint); } xPos被声明为yPos字段。每当if语句为true时,我都需要传递staticxPos,然后根据yPos的数据在onDraw方法中绘制圆。任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

只需在您的视图中添加setXY()方法并从活动中调用它即可。在该方法内,检查(分配之前)新值是否与旧值不同,如果有,请调用invalidate(),这将使视图再次呈现。最后,将新值分配给视图的x和y变量。