BottomNavigation 初始 setCurrentItem 未显示片段并且重新启动片段失败

Par*_*dox 1 android android-fragments bottomnavigationview android-bottomnav android-bottom-nav-view

我有一个 Main Activity,它使用 TabSelectedListener 来显示 AHBottomNavigation 菜单的片段。名为“FirstFragment”的片段包含一个 FragmentPagerAdapter,它允许用户在两​​个选项卡之间滑动,每个选项卡都有自己的片段,称为 FirstTabInFirstFragmentFragment 和 SecondTabInFirstFragmentFragment(为简单起见重新命名)。

我的问题是:

一种)。启动 Main Activity 时,会选择“First”底部导航菜单项,但不会启动“FirstFragment”。因此,它以空白屏幕显示选择的正确项目。如果我再次点击菜单项,它只会启动第一个片段。

b)。一旦 FirstFragment 被正确启动并显示在屏幕上(通过 a 中的临时修复),如果我选择一个不同的菜单项(即导航到 SecondFragment)然后再次选择 FirstFragment 的菜单项,里面的两个选项卡它是空白的。此外,两个标签的片段之间的滑动不起作用并被“卡住”,因此您必须将其一直拉到一侧或一直拉到另一侧。

希望我已经清楚地解释了我的问题 - 如果我遗漏了什么,我可以提供更多细节。
请注意,我正在使用com.aurelhubert.ahbottomnavigation.AHBottomNavigation
以下是相关文件:

主活动.java :

public class MainActivity extends AppCompatActivity{

private AHBottomNavigationAdapter navigationAdapter;
private AHBottomNavigationViewPager viewPager;
private AHBottomNavigation bottomNavigation;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Add menu items to bar
    bottomNavigation = (AHBottomNavigation) findViewById(R.id.bottom_navigation);
    this.createNavItems();

    bottomNavigation.setOnTabSelectedListener(new AHBottomNavigation.OnTabSelectedListener() {
        @Override
        public boolean onTabSelected(int position, boolean wasSelected) {

            //show fragment
            if (position==0)
            {
                FirstFragment firstFragment=new FirstFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_id,firstFragment).commit();
            }else  if (position==1)
            {
                SecondFragment secondFragment=new SecondFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_id, secondFragment).commit();
            }else  if (position==2)
            {
                ThirdFragment thirdFragment=new ThirdFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_id,thirdFragment).commit();
            }else{
                FourthFragment fourthFragment=new FourthFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.content_id,fourthFragment).commit();
            }

            return true;
        }
    });
}

private void createNavItems(){
    navigationAdapter = new AHBottomNavigationAdapter(this, R.menu.navigation);
    navigationAdapter.setupWithBottomNavigation(bottomNavigation);

    // set current item
    bottomNavigation.setCurrentItem(0);
}
Run Code Online (Sandbox Code Playgroud)

活动_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_id"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <com.aurelhubert.ahbottomnavigation.AHBottomNavigation
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"/>

</android.support.design.widget.CoordinatorLayout>
Run Code Online (Sandbox Code Playgroud)

FirstFragment.java:

public class FirstFragment extends Fragment {

    private FragmentActivity mContext;

    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);    

        // Set the content of the activity to use the activity_main.xml layout file
        //setContentView(R.layout.activity_first);

        // Find the view pager that will allow the user to swipe between fragments
        ViewPager viewPager = (ViewPager) getView().findViewById(R.id.viewpager);

        // Create an adapter that knows which fragment should be shown on each page
        // using getFragmentManager() will work too
        FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(mContext.getSupportFragmentManager(), mContext);

        // Set the adapter onto the view pager
        viewPager.setAdapter(adapter);

        TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    /**
     * Override to set context.  This context is used for getSupportFragmentManager in onCreateView
     * @param activity
     */
    @Override
    public void onAttach(Activity activity) {
        mContext=(FragmentActivity) activity;
        super.onAttach(activity);
    }

}
Run Code Online (Sandbox Code Playgroud)

fragment_first.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.design.widget.TabLayout
            android:id="@+id/sliding_tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabBackground="@color/firstTabBackground"
            app:tabIndicatorColor="@color/firstTabIndicatorColor"/>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1"/>

    </LinearLayout>


</android.support.constraint.ConstraintLayout>
Run Code Online (Sandbox Code Playgroud)

FirstFragmentPagerAdapter.java:

public class FirstFragmentPagerAdapter extends FragmentPagerAdapter {

    private Context context;

    public FirstFragmentPagerAdapter(FragmentManager fm, Context mContext){
        super(fm);
        context = mContext;
    }


    /**
     * The ViewPager asks the adapter for the fragment at a given position,
     * i.e. for the 1st fragment, the ViewPager asks for the fragment at
     * position 1.
     * @param position
     * @return
     */
    @Override
    public Fragment getItem(int position){
        if (position == 0){
            return new FirstTabInFirstFragmentFragment();
        }
        else{
            return new SecondTabInFirstFragmentFragment();
        }
    }

    /**
     * On launch, the ViewPager asks the adapter how many pages there will be.
     * Here, our adapter returns how many pages there will be.
     * @return
     */
    @Override
    public int getCount() {return 2;}

    @Override
    public CharSequence getPageTitle(int position) {

        switch(position){
            case 0:
                return context.getResources().getString(R.string.first_tab_in_first_fragment_page_title);
            case 1:
                return context.getResources().getString(R.string.second_tab_in_first_fragment_page_title);
            default:
                return null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Par*_*dox 5

我能够分两步解决这个问题。首先,在我的主要活动方法 createNavItems 中,除了执行 a 之外bottomNavigation.setCurrentItem(0);,我还必须content_id使用默认片段手动更新 CoordinatorLayout(具有 ID ):

getSupportFragmentManager().beginTransaction().replace(R.id.content_id, new FirstFragment()).commit();
Run Code Online (Sandbox Code Playgroud)

接下来,为了解决 TabLayout 问题,我不得不更改这一行:

FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(mContext.getSupportFragmentManager(), mContext);
Run Code Online (Sandbox Code Playgroud)

FirstFragmentPagerAdapter adapter = new FirstFragmentPagerAdapter(getChildFragmentManager(), mContext);
Run Code Online (Sandbox Code Playgroud)

这样做的原因是,当使用 ViewPager 将 Fragment 嵌套在其他 Fragment 中时,getFragmentManager()用于管理 Fragment 内的 Fragment 而mContext.getSupportFragmentManager()用于活动。