Android ViewPager子片段加载但标签不加载

时间:2015-07-28 10:54:33

标签: java android android-layout android-fragments

我在一个片段中使用ViewPager,每个标签都会加载一个子片段,这样可以很好地加载子片段,但问题是标签可点击名称所在的标签本身是没有显示,也没有响应点击事件。我通过选择前一个片段中的recyclerview中的元素来到达此屏幕。

预期的布局结构如下: Expected Layout

但问题在于,尽管其他所有内容都可以正常加载,我可以侧滑以切换子片段,但标签栏根本不会加载,我只是得到了这个:

Current Flawed layout

我不确定是什么导致了这种情况,但是当我旋转屏幕并返回时,它们会出现。

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);
}}

感谢任何帮助和建议。

4 个答案:

答案 0 :(得分:1)

最后我无法找到解决方案,即使在咨询了一些经验丰富的开发人员之后,我们也只能找到一种解决方法,这只是在一个活动而不是片段中,然后是viewpager行为正如所料。我无法弄清楚它为什么不在片段内。 如果有人找到更合适的答案,请继续,但在此之前我会将此设置为接受的答案。

答案 1 :(得分:1)

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

尝试这个并使用getChildFragmentManager

启动适配器

答案 2 :(得分:0)

我会尝试登录getPageTitle,因为我认为当你旋转屏幕时,一切都被破坏了,当你重新绘制标题时mFragmentTitleList是空的,所以试着通过做类似的事情来找出发生了什么:

    @Override
    public CharSequence getPageTitle(int position) {

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

答案 3 :(得分:0)

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

如果您将TabLayoutViewPager绑定

,则无需手动处理标签点击
tabLayout.setupWithViewPager(viewPager);

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