Question

Please correct me if my OOP application is incorrect. I have a custom Android class at /src/myworkspace/MyObject.java that does not extend anything.

public class MyObject {
  ...

  public void methodOne() {
    ...
  }
}

Within the main activity, MyObject.methodOne() is called.
How would I manipulate view objects in methodOne?
For example somthing similar to

mButton = (Button) findViewById(R.id.button_one);
mButton.setOnClickListener(mButtonListener);

The methods of MyObject are reused in many activities. If this approach is incorrect, where should the repeatable code be stored?

Was it helpful?

Solution

I would suggest MyObject receive a view as a parameter:

public class MyObject {
...
  public void methodOne(Button button) {
   ...
  }
}

The just call it this way from your activity:

... activity code ....
MyObject obj = new MyObject();
Button button = (Button) findViewById(R.id.button_one);
obj.methodOne(button);
.... more activity code.

You can use other approaches too :

Bind MyObject to activity in the constructor :

MyObject(Activity owner) {
   .. assign activity to member
}

Use Object as a nested inner class.

 Activity
   class MyObject {

Each has it's merits or gotchyas, I personally would stick with passing a view by parameter, it is the most loosly coupled, and IMO the simplest and least error prone.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top