见到一种不依赖viewpager实现多个fragment来回切换的实现,潜意识里认为能减少不少出问题的因素。在这里做下记录。
布局文件:
<!--activity_sleep_data.xml--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tl="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical" tools:context="com.meddo.zzh.bed.SleepDataActivity"> <include layout="@layout/title_bar_bg_white" /> <com.flyco.tablayout.SegmentTabLayout android:id="@+id/segment_tab_layout" android:layout_width="match_parent" android:layout_height="35dp" android:layout_gravity="center_horizontal" tl:tl_indicator_color="@color/colorPrimary" tl:tl_indicator_corner_radius="0dp" tl:tl_tab_padding="20dp" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_weight="1" android:orientation="horizontal"> <fragment android:id="@+id/fragment_heart" class="com.meddo.zzh.bed.HeartFragment" android:layout_width="match_parent" android:layout_height="match_parent"></fragment> <fragment android:id="@+id/fragment_breath" class="com.meddo.zzh.bed.BreathFragment" android:layout_width="match_parent" android:layout_height="match_parent"></fragment> <fragment android:id="@+id/fragment_off_bed" class="com.meddo.zzh.bed.OffBedFragment" android:layout_width="match_parent" android:layout_height="match_parent"></fragment> <fragment android:id="@+id/fragment_turn_over" class="com.meddo.zzh.bed.TurnOverFragment" android:layout_width="match_parent" android:layout_height="match_parent"></fragment> </LinearLayout> </LinearLayout>
代码:
public class SleepDataActivity extends BaseActivity { private SegmentTabLayout mSegmentTabLayout; private FragmentManager mFragmentManager; private Fragment[] fragments; private int[] mFragmentIds = new int[]{R.id.fragment_heart, R.id.fragment_breath, R.id.fragment_off_bed, R.id.fragment_turn_over}; @Override public void initView() { setContentView(R.layout.activity_sleep_data); mSegmentTabLayout = (SegmentTabLayout) findViewById(R.id.segment_tab_layout); mSegmentTabLayout.setTabData(new String[]{"心率", "呼吸", "离床", "体动"}); mFragmentManager = getSupportFragmentManager(); fragments = new Fragment[]{mFragmentManager.findFragmentById(mFragmentIds[0]), mFragmentManager.findFragmentById(mFragmentIds[1]), mFragmentManager.findFragmentById(mFragmentIds[2]), mFragmentManager.findFragmentById(mFragmentIds[3]),}; mSegmentTabLayout.setOnTabSelectListener(new OnTabSelectListener() { @Override public void onTabSelect(int position) { for (int i = 0; i < fragments.length; i++) { mFragmentManager.beginTransaction().hide(fragments[i]).commit(); } FragmentTransaction transaction = mFragmentManager.beginTransaction(); transaction.show(fragments[position]); transaction.commit(); } @Override public void onTabReselect(int position) { } }); } }
直接从项目中复制的代码。(SegmentTabLayout是tabar控件,点击切换fragment。详见FlycoTabLayout)