gpt4 book ai didi

java - 从类更改 Activity 中的对象

转载 作者:行者123 更新时间:2023-12-02 13:24:04 26 4
gpt4 key购买 nike

我有一个Activity,它有两个不同类的对象

我有一个 CanvasLayout 类,需要在某些条件下更改 Activity 的对象。

我该怎么做?

当前计数 Activity

public class CurrentlyCountingActivity extends AppCompatActivity {

CanvasLayout canvasLayout;

//I want to call one of the carCommands and
//pathCoordinates functions from canvasLayout
CarCommands carCommands;
PathCoordinates pathCoordinates;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
canvasLayout = new CanvasLayout(this);
setContentView(canvasLayout);
carCommands = new CarCommands();

//because I don't want the car to be moving initially
carCommands.setAbsoluteSpeed(0, 0);
}

//Other functions dealing with Path coordinates
}

CanvasLayout类

public class CanvasLayout extends SurfaceView implements Runnable {

... initializations here

@Override
public void run() {

prepBrush();

while(canDraw) {
..other irrelevant code

motionPoint();

...more code


if((pointX == INITIAL_X) && (pointY == INITIAL_Y)) {
canDraw = false;
//I would like to have something like
//carCommands.setAbsoluteSpeed(0, 0); here
}
}
}


private void motionPoint() {
//I want to call pathCoordinates of Activity in CanvasLayout
pathCoordinates.trackPathCoordinates();
pointX = pathCoordinates.getX();
pointY = pathCoordinates.getY();

}

}

最佳答案

使用Interface .

SurfaceView

private OnCanvasListener onCanvasListener;
public class CanvasLayout extends SurfaceView implements Runnable {

public interface OnCanvasListener{

public void doSomething();
}

public CanvasLayout(Context this){
onCanvasListener = (OnCanvasListener)this;
}


@Override
public void run() {

prepBrush();

while(canDraw) {
..other irrelevant code

motionPoint();

...more code


if((pointX == INITIAL_X) && (pointY == INITIAL_Y)) {
canDraw = false;
//I would like to have something like
//carCommands.setAbsoluteSpeed(0, 0); here
onCanvasListener.doSomething(); // invoke interface method

}
}
}

}

在activity中实现接口(interface)

public class CurrentlyCountingActivity extends AppCompatActivity implements OnCanvasListener  {

CanvasLayout canvasLayout;

//I want to call one of the carCommands and
//pathCoordinates functions from canvasLayout
CarCommands carCommands;
PathCoordinates pathCoordinates;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
canvasLayout = new CanvasLayout(this);
setContentView(canvasLayout);
carCommands = new CarCommands();

//because I don't want the car to be moving initially
carCommands.setAbsoluteSpeed(0, 0);
}

//Other functions dealing with Path coordinates

@Override
public void doSomething(){

// implement your logic here.
}

}

对于任何拼写错误,我们深表歉意。希望这会有所帮助。

关于java - 从类更改 Activity 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43445537/

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