Philippe Goncalves
Philippe Goncalves

Reputation: 193

Best practice to access Activity from Views

I have a question that seems simple but I cannot figure out what is the best practice for that :)

What is the best practice to access from a View, a method on the Activity that launched the View?

For example, I have an Activity with a layout that contains a Button and a Textfield. I want when I click on the Button, to call a method on my Activity that update the Textfield with some value. I come with multiple solutions:

1 - Inner class for the OnClickListener directly on the Activity so I can the method of the Activity with MyActivity.this.updateTextField() on onClick method

2 - Outer class for the OnClickListener, on my onClick method I can do: ((MyActivity)getContext()).updateTextField()

3 - Reference the Activity on my OnClickListener class when I instantiate it: myButton.setOnClickListener(new MyOnclickListener(MyActivity));

I don´t want solution 1 because I don´t like that much inner class and I want reusable code. Solution 2 seems good but can produce error on runtime if my context is not an activity. Solution 3 seems good also but "heavy".

What is the best practice on Android to tell from the View to its Actitity that something needs to be done on the Activity?

Thanks!

Upvotes: 1

Views: 381

Answers (2)

MByD
MByD

Reputation: 137312

Although I mostly find myself end up with inner classes, there are other options. You can create an interface like the following and let your activity implement it:

public interface UpdateableTextField {
    public void updateTextField();
}

Now let the Activities that you want implement this interface.

Now, create a class that implements View.OnclickListener and set the constructor to get UpdateableTextField as a parameter:

public class MyListener implements View.OnclickListener {
    UpdateableTextField updatable;

    public MyListener(UpdateableTextField updatable) {
        this.updateable = updatable;
    }

    @Override public void onClick(View v) {
        // do some stuff
        updateable.updateTextField();
    }
}

And last, in the Activity:

public class MyActivity extends Activity implementes UpdateableTextField{
    @Override public void onCreate(Bundle savedInstanceState) {
        // usuall stuff
        MyListener listener = new MyListener(this);
        someView.setOnClickListener(listener);
        // other stuff
    }

    @Override public void updateTextField() {
        // well, update the text field :)
    }
}

Upvotes: 0

Aashish Bhatnagar
Aashish Bhatnagar

Reputation: 2605

implement activity with onclickListener and add unimplemented method onclick just check for the view to see which button is clicked incase you are using multiple buttons

Upvotes: 1

Related Questions