我正在使用SDK API級別23, 安卓應用程序我有一個屏幕與選項卡布局與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>
根據android的內存管理,由「FragmentPagerAdapter」完成。它創建並保存內存中的下一個和前一個片段,輕鬆地進行輕掃/更改。 –