【问题标题】:How to access variables from main activity to surfaceview Android?如何访问从主要活动到surfaceview Android的变量?
【发布时间】:2013-06-30 01:10:51
【问题描述】:
我在主要活动中有两个按钮以编程方式制作,没有 xml。
按钮应该在surfaceview上移动位图,我该如何实现?
here is one of the Buttons:
Button1.setOnClickListener(this);
}
public void onClick(View v) {
//I want to access variable x and y of surfaceview
if (x==230)
x=x +20;
invalidate();
}
【问题讨论】:
标签:
button
android-canvas
surfaceview
onclicklistener
translate-animation
【解决方案1】:
如果您创建了 SurfaceView 的子类,其中您有 x 和 y 变量,最佳做法是为这些变量创建 setter 和 getter(我将其称为 setPositionX() 而不是 setX(),因为SurfaceView已经有了那个方法):
public class MySurfaceView extends SurfaceView {
private int x;
private int y;
public void setPositionX(int x) {
this.x = x;
}
public void setPositionY(int y) {
this.y = y;
}
public int getPositionX() {
return x;
}
public int getPositionY() {
return y;
}
}
在您的活动中:
private MySurfaceView mySurfaceView;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Create SurfaceView and assign it to a variable.
mySurfaceView = new MySurfaceView(this);
// Do other initialization. Create button listener and other stuff.
button1.setOnClickListener(this);
}
public void onClick(View v) {
int x = mySurfaceView.getPositionX();
int y = mySurfaceView.getPositionY();
if (x == 230) {
mySurfaceView.setPositionX(x + 20);
}
invalidate();
}
【解决方案2】:
如果您希望将值传递回原始活动,则应使用 startActivityForResult。
然后您可以在 onActivityResult 回调中访问它们