Implementing a TabListener using the Support Library

前端 未结 5 1681
终归单人心
终归单人心 2020-12-14 02:45

I am trying to implement Tab Navigation, but I want to make sure people that have older versions of Android can still use my application.

The app in mind ATM is fai

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 03:14

    I wanted to implement @nelson-ramirez but had an error accessing mActivity, so this is a combination of those two answers, and works for my project, which uses a tab navigation with Facebook login (which requires support.v4 library). the keys are, creating a private mActivity that you then pass in and assign when initiating the listener, and creating your own Fragment Transaction, not using the one from the argument. Also, change the main activity to FragmentActivity, using v4 library, which allows access to getSupportFragmentManager().

    public class MyTabListener implements ActionBar.TabListener{
        private Fragment fragment;
        private FragmentActivity mActivity;
    
        public MyTabListener(Fragment fragment, FragmentActivity activity){
            this.fragment = fragment;
            this.mActivity = activity;
        }
    
        @Override
        public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
            android.support.v4.app.FragmentTransaction fft = mActivity.getSupportFragmentManager().beginTransaction();
            fft.replace(R.id.fragment_container, fragment);
            fft.commit();
        }
    
        @Override
        public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
            android.support.v4.app.FragmentTransaction fft = mActivity.getSupportFragmentManager().beginTransaction();
            fft.remove(fragment);
        }
    
        @Override
        public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
    
        }
    }
    

提交回复
热议问题