简体   繁体   中英

How to change the selected tab on button click?

I have followed the tutorial found here:

Implementing Fragment Tabs in Android

and I have it working properly, but I wanted to be able to switch the fragments on button click, not just on tab selection. So inside of FragmentTab1() I have added an ImageButton that lets me switch out my fragments, and open FragmentTab2() .

This is the code inside of FragmentTab1() in OnCreateView() :

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_form1, container, false);
    btnFragment1 = (ImageButton) rootView.findViewById(R.id.next);

    btnFragment1.setOnClickListener(btnFragmentOnClickListener);

    return rootView;
}

This is the code for my button:

Button.OnClickListener btnFragmentOnClickListener
        = new Button.OnClickListener(){

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Fragment newFragment;

        newFragment = new FragmentTab2();

        // Create new transaction
        FragmentTransaction transaction = getFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();
    }};
}

This works properly to switch out the fragments.

My question is : How do I get the selected tab to have the blue line underneath the text in the tab itself? Any help would be appreciated!

Edit: I am not using a TabHost so this makes the solution trickier, I am using ActionBar.TabListener.

adding these two lines did the trick inside of my button handler:

ActionBar actionBar = (ActionBar)getActivity().getActionBar();
actionBar.setSelectedNavigationItem(1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM