Saeid
Saeid

Reputation: 2321

Different action for button (OnClickListener) in distinct fragment

i have a FragmentActivity with three Fragment and want to handle setOnClickListener in each of fragment with Different action, but Button return action for last fragment.

now , how possible to make Different action for button in distinct fragment?

in FragmentActivity :

    @Override
    public Fragment getItem(int position) {
        FrameLayout frameLayout=reg_next;
        switch (position) {
        case 0: // Fragment # 0 - This will show FirstFragment
            return o1.newInstance(0, "1",vpPager,ButtonNext);
        case 1: // Fragment # 0 - This will show FirstFragment different title
            return o2.newInstance(1, "2",vpPager,ButtonNext);
        case 2: // Fragment # 0 - This will show FirstFragment different title
            return o3.newInstance(2, "3");   
        default:
            return null;
        }
    }

in Fragments:

{
 ...
  ButtonNext.setOnClickListener(this);
 ...
}

In Fragment 1:

    @Override
public void onClick(View v) {
    Toast.makeText(getActivity(), "Fragment Number  1",0).show();

}

In Fragment 2:

    @Override
public void onClick(View v) {
    Toast.makeText(getActivity(), "Fragment Number 2",0).show();

}

But always return Fragment Number 2 setOnClickListener event ,Even when current fragment is first fragment (Fragment 1)

there are any way for multi-handling in distinct fragment?

Upvotes: 0

Views: 96

Answers (1)

Juan Aguilar Guisado
Juan Aguilar Guisado

Reputation: 1701

In your case, I would do this:

  1. Define onClick listener in your activity, not in your fragments. This will act like a dispatcher.
  2. Set different ID to every button (in order to be able to distinguish them).
  3. Bind a variable to indicate the current fragment. Every time you load a fragment (I suppose in your getItem, but I'm not sure), set your variable to something which identifies the fragment (for instance .class, or a String value).
  4. With if/else select the action for the button depending on your "bind variable", and call a method declared in the fragment which handles the event.(for instance: buttonFragment3Clicked(View v)), declared in your third fragment.

I hope this helps!! :)

Upvotes: 1

Related Questions