Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple onClickListener for one button

I have an ImageButton I can access in my Activity and in my Fragment. I want actions to be done in both of those said classes so I implemented an onClickListener for both of them.

     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        ImageButton imageButton = (ImageButton) findViewById(R.id.my_image_button);
        imageButton.setOnClickListener(new OnClickListener() ...);
    }

And the same simple piece of code for the fragment launched by this activity (But in onViewCreated).

I tried it and only the Fragment's onClickListener is triggered.

So, here is my question, is there a way to make my button trigger both Activity's and Fragment's onClickListener ?

I know I could call a Fragment's method from the Activity's onClick, but it would be so much simpler to just trigger it inside the Fragment aswell.

EDIT :

I am not willing to do this through two OnClickListener at any cost, it was just in case there were a simpler way than Activity to Fragment callbacks (in my case).

As 空気嫁 said, a second onClickListener would disable the first one. In that case, only callbacks left.

Plus, after thinking a bit about it, it would make the code easier to understand too. Callbacks, yeah !

like image 720
Cedric Avatar asked Jan 06 '23 17:01

Cedric


1 Answers

View.setOnClickListener only supports set one listener. If you call it twice, the later listener will cover the former listener and only the later listener will be notified. So call a Fragment's method from the Activity's onClick seems good for you. And if the ImageButton is defined in Activity's layout, it is good to deal with it only in Activity such as notifying others and exposing some methods.

like image 177
空気嫁 Avatar answered Jan 08 '23 06:01

空気嫁