android where to put OnClickListener OOP-wise?

Suppose I have a MyTextView class that extends TextView. The myTextView Objects should be clickable.

On one hand, it seems that the OnClickListener should be in the MyTextView class since I will be using a few of those, and I don’t want to set an OnClickListener to each one. If the OnClickListener is in the MyTextView class, it will only be written once. Moreover, all myTextView objects perform the same thing when clicked.

On the other hand, these objects need to update the UI and some variables in the activity they’re in. I don’t have access to these variables and UI objects from within MyTextView class and it doesn’t feel right to send reference to all of them via the costructor.

What would be the right thing to do OOP-wise ?

Answer

you can do so

class MyTextView extends TextView implements View.OnClickListener{

    public MyTextView(Context context) {
        super(context);
        this.setOnClickListener(this);
    }

    public static interface MyTextListener{
        public void updateUI();
    }

    @Override
    public void onClick(View v) {
        if(getContext() instanceof MyTextListener){
            ((MyTextListener)getContext()).updateUI();
        }
    }
}

continue to implement the interface in activity

public class MainActivity extends Activity implements MyXextView.MyTextListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);    
    }

    @Override
    public void updateUI() {
        //update here
    }

}

Leave a Reply

Your email address will not be published. Required fields are marked *