0

I'm writing a program that has two classes, one that extends Activity and another that extends SurfaceView. The activity has an object of the SurfaceView class. I am trying to use setters and getters to send data between these two classes, but every time I try, eclipse says that the methods for setting and getting need to be static. I can't do this because I don't want them to be static.

The Activity class contains the following methods:

public float getxTouch(){
return xTouch;
}
public float getyTouch(){
return yTouch;
}

The SufaceView class contains the following code:

xpos = ActivityClass.getxTouch();
ypos = ActivityClass.getyTouch();

How might I fix this without making the methods static?

4

2 回答 2

1

您可以使用 Intent 在 Activity 和您的类之间传输变量的引用。

首先,让我们创建一个包含变量的可序列化类:

class XYTouch implements Serializable{
  public static final String EXTRA = "com.your.package.XYTOUCH_EXTRA";

  private float xTouch;

  public void setX(String x) {
      this.xTouch = x;
  }

  public String getX() {
      return xTouch;
  }

// do the same for yTouch    
}

然后,在您的活动中onCreate,创建一个新的 XYTouch 对象并使用 set 和 get 方法设置其 xTouch 和 yTouch 属性。然后写

Intent intent = new Intent(this, OtherClass.class);
intent.putExtra(XYTouch.EXTRA, xytouchobject);
startActivity(intent);

在您想要访问这些变量的其他类 (OtherClass) 中:

public void onCreate(Bundle savedInstance){
   // ....
   XYTouch xytouch = (XYTouch) getIntent().getSerializableExtra(XYTouch.EXTRA);
   // ....
}

然后,您可以在类中的任何位置使用 XYTouch 的 get 和 set 方法来引用 xTouch 和 yTouch。

另一种方法是从您自己的扩展 Application 并保留对这些变量的引用的类中检索它。然后,您将使用 Activity 上下文来读取它们。

于 2012-07-25T21:59:40.640 回答
0

将活动类的引用传递给您的表面类。做这样的事情,所以你不必使方法静态。

在您的 SurfaceView 类中:

Activity foo;

//some method to set foo:

public void setFoo(Activity foo) {
this.foo = foo;
}

// Then you can simple call your getX() and getY() methods like this:

foo.getX(); and foo.getY();

从您的活动课程中:

yourSurfaceViewInstance.setFoo(this);
于 2012-07-25T19:19:44.407 回答