3
votes

I have many buttons declared in an xml layout file, and use this layout for a fragment.


button android:id="@+id/button1" android:onClick="onClickButton"/>
button android:id="@+id/button2" android:onClick="onClickButton"/>
....
button android:id="@+id/buttonN" android:onClick="onClickButton"/>

It's disappointed that "onClickButton" events are catched in the host activity, not in my fragment. Of course, in my fragment I can manually solve this problem as follow:


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_content, container, false);

    Button button1 = (Button) view.findViewById(R.id.button1);
    button1.setOnClickListener(...);

    ... etc

    Button buttonN = (Button) view.findViewById(R.id.buttonN);
    buttonN.setOnClickListener(...);

is there any explicit way to handle onClickbutton events in Fragment?

3

3 Answers

1
votes

Unfortunately doing that in code is the only way when just using Android SDK.

Have you tried something custom? AndroidAnnotations or RoboGuice make it less verbose.

6
votes

The method mentioned by you is the standart way of doing it:

 Button buttonN = (Button) view.findViewById(R.id.buttonN);
 buttonN.setOnClickListener(...);

Just let your Fragment implement OnClickListener then you can set it to listen to all buttons

Button buttonN = (Button) view.findViewById(R.id.buttonN);
buttonN.setOnClickListener(this);
0
votes

Hmm. Interesting. I never try these code. It is just a theory. I use this OnClickListener a lot in other situation.

====================

Buttons can use the same OnClickListener if they have different id. That's easy part.

One OnClickListener can call another OnClickListener.

Like this...

OnClickListener other;
OnClickListener demo = new OnClickListener() {
    void onClick(View v) {
        if(other != null)other.onClick(v);
    }
}

So, set an ArrayList in your Activity. When Fragment created and attached to Activity, put your OnClickListener into it. When Fragment destroy and detached, remove your OnClickListener.

ArrayList<OnClickListener> list = new ArrayList<>();
OnClickListener demo = new OnClickListener() {
    void onClick(View v) {
        for(OnClickListener demo : list) {
             demo.onClick(v);
        }
    }
};

This module should do what you want. Maybe fix some code.