当前位置: 代码迷 >> java >> Android ViewPager子片段加载但选项卡不加载
  详细解决方案

Android ViewPager子片段加载但选项卡不加载

热度:107   发布时间:2023-08-04 09:30:05.0

我在一个片段中使用ViewPager,该片段在每个选项卡中加载一个子片段,并且可以很好地加载子片段,但是问题是这些选项卡本身(选项卡可点击名称所在的位置)没有显示,也不响应点击事件。 我通过在上一个片段的recyclerview中选择一个元素来到达此屏幕。

预期的布局结构如下:

但是问题是,尽管其他所有内容都可以正常加载,并且我可以侧向滑动以切换子片段,但标签栏根本无法加载,我得到的是:

我不确定是什么原因造成的,但是当我旋转屏幕并向后旋转时,它们就会出现。

MainActivity类

public class MainActivity extends AppCompatActivity {

private final static int PROFILE_FRAGMENT = 1;
private final static int PRIZES_FRAGMENT = 2;
private final static int STORES_FRAGMENT = 3;
private final static int ABOUT = 4;
private int currentFragment = 3;
private String currentFragmentName = "StoresListFragment";
public int HEADER_IMAGE = R.drawable.avatar;

private DrawerLayout drawer;
private List<DrawerItem> dataList;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    DatabaseHandler db = new DatabaseHandler(getApplicationContext());
    FragmentManager fm = getSupportFragmentManager();

    if (getIntent().getStringExtra("STORE_DETAILS") != null) {
        openFragment(new StoreDetailsFragment());
        setTitle(getString(R.string.title_store_details));
    }
    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    if (mToolbar != null) {
        setSupportActionBar(mToolbar);
    }
    RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
    mRecyclerView.setHasFixedSize(true);
    dataList = new ArrayList<>();
    addItemsToDataList();
    NavDrawerAdapter mAdapter = new NavDrawerAdapter(dataList, this, db.getClientName(), db.getPoints(), HEADER_IMAGE);
    mRecyclerView.setAdapter(mAdapter);
    RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this);
    mRecyclerView.setLayoutManager(mLayoutManager);
    drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);
    drawer.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
    };
    drawer.setDrawerListener(mDrawerToggle);
    mDrawerToggle.syncState();
    onTouchDrawer(currentFragment);
    final GestureDetector mGestureDetector =
            new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {
                @Override
                public boolean onSingleTapUp(MotionEvent e) {
                    return true;
                }
            });
    mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
        @Override
        public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
            View child = recyclerView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());

            if (child != null && mGestureDetector.onTouchEvent(motionEvent)) {
                drawer.closeDrawers();
                onTouchDrawer(recyclerView.getChildLayoutPosition(child));
                return true;
            }
            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView rv, MotionEvent e) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });
}

private void addItemsToDataList() {
    dataList.add(new DrawerItem(getString(R.string.title_profile), R.mipmap.ic_action_profile));
    dataList.add(new DrawerItem(getString(R.string.title_prizes), R.mipmap.ic_action_prizes));
    dataList.add(new DrawerItem(getString(R.string.title_stores), R.mipmap.ic_action_sales));
    dataList.add(new DrawerItem(getString(R.string.title_about), R.mipmap.ic_action_about));
}

public void openFragment(final Fragment fragment) {
    if (!fragment.toString().equalsIgnoreCase(currentFragmentName)) {
        // update the transfer content by replacing fragments
        currentFragmentName = fragment.toString();
        switchContent(fragment);
    }
    getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).commitAllowingStateLoss();
}

private void onTouchDrawer(final int position) {
    currentFragment = position;
    switch (position) {
        case PROFILE_FRAGMENT:
            openFragment(new ProfileFragment());
            setTitle(getString(R.string.title_profile));
            break;
        case PRIZES_FRAGMENT:
            openFragment(new PrizesListFragment());
            setTitle(getString(R.string.title_prizes));
            break;
        case STORES_FRAGMENT:
            openFragment(new StoresListFragment());
            setTitle(getString(R.string.title_stores));
            break;
        case ABOUT:
            openFragment(new AboutFragment());
            setTitle(getString(R.string.title_about));
            break;
        default:
    }
}

/*
 * helper to switch content with backstack
 */
public void switchContent(Fragment fragment) {

    getSupportFragmentManager().beginTransaction()
            .replace(R.id.container, fragment)
                    // add to backstack
            .addToBackStack(fragment.getClass().getSimpleName())
            .commitAllowingStateLoss();
}


@Override
protected void onResume() {
    if (getIntent().getStringExtra("SALES_LIST") != null) {
        openFragment(new StoreDetailsFragment());
        setTitle(getString(R.string.title_store_details));

    } else if (getSupportFragmentManager().getBackStackEntryCount() <= 0) {
        openFragment(new StoresListFragment());
        setTitle(getString(R.string.title_stores));
    }
    super.onResume();
}

}

有问题的片段:

public class StoreDetailsFragment extends Fragment {

private ViewPager viewPager;
private Store storeSelected = null;
private TextView storeName;
private ImageView bannerImage;
private TextView storesubtitle;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_store_details, container, false);

    viewPager = (ViewPager) rootView.findViewById(R.id.tabanim_viewpager);
    TabLayout storeTabLayout = (TabLayout) rootView.findViewById(R.id.tabanim_tabs);
    setupViewPager(viewPager);

    storeTabLayout.setupWithViewPager(viewPager);
    storeTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {

            viewPager.setCurrentItem(tab.getPosition());
            switch (tab.getPosition()) {
                case 0:
                    Toast.makeText(getActivity(), "Sales List", Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    Toast.makeText(getActivity(), "Store Description", Toast.LENGTH_SHORT).show();
                    break;
                case 2:
                    Toast.makeText(getActivity(), "Store Ratings", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    Toast.makeText(getActivity(), "Images", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });
    bannerImage = (ImageView) rootView.findViewById(R.id.store_details_banner_image);
    storeName = (TextView) rootView.findViewById(R.id.text_store_details_name);
    storesubtitle = (TextView) rootView.findViewById(R.id.text_store_details_subtitle);
    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    // Set title
    getMainActivity().setTitle(R.string.title_store_details);
}

protected MainActivity getMainActivity() {
    return (MainActivity) getActivity();
}

}

问题片段的布局:

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

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsing_toolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <ImageView
                android:id="@+id/store_details_banner_image"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="?attr/actionBarSize"
                android:background="@drawable/white_placeholder"
                android:contentDescription=""
                android:fitsSystemWindows="true"/>

            <LinearLayout
                android:id="@+id/smth"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom"
                android:layout_marginBottom="?attr/actionBarSize"
                android:background="#ffffff"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/text_store_details_name"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="18dp"
                    android:layout_marginTop="40dp"
                    android:textColor="#333"
                    android:textSize="15sp"
                    android:textStyle="bold"/>

                <TextView
                    android:id="@+id/text_store_details_subtitle"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="5dp"
                    android:layout_marginStart="13dp"
                    android:layout_marginTop="3dp"
                    android:drawableLeft="@mipmap/ic_action_store_house"
                    android:gravity="center_vertical"
                    android:textAppearance="?android:attr/textAppearanceMedium"
                    android:textColor="#333"/>
            </LinearLayout>

            <android.support.v7.widget.Toolbar
                android:id="@+id/anim_toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="@color/transparent"
                app:layout_collapseMode="parallax"
                app:layout_scrollFlags="scroll|enterAlways"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

            <android.support.design.widget.TabLayout
                android:id="@+id/tabanim_tabs"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:layout_gravity="bottom"
                android:visibility="visible"
                app:tabGravity="center"
                app:tabIndicatorColor="#F1514A"
                app:tabMode="scrollable"
                app:tabSelectedTextColor="@android:color/white"
                app:tabTextColor="#99ffffff"/>

        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/tabanim_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>

</android.support.design.widget.CoordinatorLayout>

和ViewPagerAdaper:

public class StoreDetailsViewPagerTabAdaper extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();

public StoreDetailsViewPagerTabAdaper(FragmentManager manager) {
    super(manager);
}

@Override
public android.support.v4.app.Fragment getItem(int position) {

    return mFragmentList.get(position);
}

@Override
public int getCount() {
    return mFragmentList.size();
}

public void addFrag(android.support.v4.app.Fragment fragment, String title) {
    mFragmentList.add(fragment);
    mFragmentTitleList.add(title);
}

@Override
public CharSequence getPageTitle(int position) {
    return mFragmentTitleList.get(position);
}}

任何帮助和建议,表示赞赏。

最后,我找不到解决方案,即使咨询了一些更有经验的开发人员,我们也只能找到一种解决方法,就是将其放在一个活动中而不是一个片段中,然后viewpager会按预期运行。 我不知道为什么它不在片段中。 如果有人找到了更合适的答案,请继续,但是在此之前,我将其设置为可接受的答案。

tabLayout.post(new Runnable() {
        @Override
        public void run() {
            tabLayout.setupWithViewPager(viewPager);
        }
    });

试试这个,并使用getChildFragmentManager启动适配器

我会尝试在getPageTitle中登录,因为我认为当旋转屏幕时,所有内容都被破坏了,当重绘标题时,mFragmentTitleList为空,因此请尝试执行以下操作来找出正在发生的情况:

    @Override
    public CharSequence getPageTitle(int position) {

    Log.d("ViewPagerAdapter", "Displaying title: "+ mFragmentTitleList.get(position));
    return mFragmentTitleList.get(position);
    }

您的TabLayout可能没有显示,因为您将其设置为高度。 尝试设置android:layout_height="wrap_content"

如果将TabLayoutViewPager绑定在一起,则TabLayout手动处理选项卡单击

tabLayout.setupWithViewPager(viewPager);

侦听器是自动创建的。 我建议删除自定义侦听器。

  相关解决方案