如何使用getter和setter方法​​的类在安卓之间传递数据如何使用、方法、数据、setter

2023-09-12 06:01:39 作者:失而复得

我正在写一个程序,有两个班,一个延伸活动和其他延伸SurfaceView。活动具有SurfaceView类的对象。我想用getter和setter方法​​来发送这两个类之间的数据,但每一次我尝试,日食说,方法来设置和获取必须是静态的。我不能这样做,因为我不希望他们是静态的。

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.

活动类包含以下方法:

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

在SufaceView类包含以下code:     XPOS = ActivityClass.getxTouch();     ypos = ActivityClass.getyTouch();

the SufaceView class contains the following code: xpos = ActivityClass.getxTouch(); ypos = ActivityClass.getyTouch();

如何才能解决这一问题未做方法静态?

how might I fix this without making the methods static?

推荐答案

您可以使用意图到你的活动和班级之间传输变量引用。

You can use Intents to transfer references of variables between your Activity and your class.

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

First, let's create a serializable class that will contain your variables:

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对象,并设置其xTouch和yTouch属性使用set和get方法。然后写

Then, in your activity's onCreate, create a new XYTouch object and set its xTouch and yTouch attributes using set and get methods. Then write

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

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

In your other class (OtherClass) in which you want access to those variables:

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

然后,您可以使用get和set XYTouch的方法类的任何地方有一个参考xTouch和yTouch。

Then, you can use get and set methods of XYTouch anywhere in your class to have a reference to xTouch and yTouch.

另一种方法是从一类自己的扩展的应用,并保持一个参考这些变量检索它。然后,你可以使用一个活动的上下文读入。

Another way would be to retrieve it from a class of your own that extends Application and keeps a reference to those variables. Then you would use an Activity context to read them in.