我正在使用SDK API级别23的Android应用程序, 我有一个带有viewpager标签布局的屏幕。问题是当我点击一个标签时,创建的下一个标签就是火!
以下是标签片段的代码:
package com.systemonline.fanscoupon.coupon_tabs;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.systemonline.fanscoupon.Base.BaseFragment;
import com.systemonline.fanscoupon.R;
import java.lang.reflect.Field;
public class CouponTab extends BaseFragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.cop_tabs_layout, null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
@Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
@Override
public void onDetach() {
super.onDetach();
try {
Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
childFragmentManager.setAccessible(true);
childFragmentManager.set(this, null);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new AllCouponsFragment();
case 1:
return new OnlyForYouCouponsFragment();
case 2:
return new MyCouponsFragment();
}
return null;
}
@Override
public int getCount() {
return int_items;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getResources().getString(R.string.all_cop);
case 1:
return getResources().getString(R.string.only_for_you);
case 2:
return getResources().getString(R.string.my_cop);
}
return null;
}
}
}
这是布局XML的代码:
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/material_blue_grey_800"
app:tabGravity="fill"
app:tabIndicatorColor="@color/orange"
app:tabMode="fixed"
app:tabSelectedTextColor="@color/orange"
app:tabTextColor="@color/white">
</android.support.design.widget.TabLayout>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v4.view.ViewPager>
答案 0 :(得分:1)
我不认为这是一种意想不到的行为。因为默认情况下ViewPager
会加载3个项目。
出于这个原因,当你去任何一个项目时,它会自动创建下一个项目&amp; onCreate()
被称为。{/ p>