How to use setters and getters to pass data between classes in android

笑着哭i 提交于 2019-12-12 05:27:32

问题


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?


回答1:


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    
}

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);

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);
   // ....
}

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.




回答2:


Pass the reference of the activity class to your surface class. Do something like this, so you don't have to make the methods static.

In your SurfaceView class:

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();

From your Activity class:

yourSurfaceViewInstance.setFoo(this);


来源:https://stackoverflow.com/questions/11656879/how-to-use-setters-and-getters-to-pass-data-between-classes-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!