本文介绍了一个按钮有多个onClickListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ImageButton,可以在我的Activity和Fragment中访问它.我希望在上述两个类中都执行操作,因此我为它们两个都实现了onClickListener.

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

此活动启动的片段的同一段简单代码(但在onViewCreated中).

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

我尝试过,只有Fragment的onClickListener被触发.

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

所以,这是我的问题,有没有办法让我的按钮同时触发Activity和Fragment的onClickListener?

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

我知道我可以从Activity的onClick调用Fragment的方法,但是同样在Fragment内触发它也要简单得多.

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.

不愿意通过两个OnClickListener 进行任何操作,以防万一有一种比Activity更简单的方式来分段回调(在我的情况下) ).

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

如空気嫁所说,第二个onClickListener将禁用第一个.在这种情况下,只剩下回调.

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 !

推荐答案

View.setOnClickListener仅支持设置一个侦听器.如果您两次调用它,则后一个侦听器将覆盖前一个侦听器,并且仅会通知后一个侦听器.因此,从Activity的onClick调用Fragment的方法似乎对您很有益.而且,如果ImageButton是在Activity的布局中定义的,则最好仅在Activity中处理它,例如通知其他对象并公开一些方法.

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.

这篇关于一个按钮有多个onClickListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:54