将官方的SlidingTabLayout.java和SlidingTabStrip.java拷到自己的项目里面。
修改布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">
<cn.treize.paperpomodoro.view.SlidingTabLayout android:id="@+id/tabs" android:background="@color/color_primary" android:layout_width="match_parent" android:layout_height="wrap_content" />
<android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp" /> </LinearLayout>
|
修改MainActivity.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| public class MainActivity extends ActionBarActivity {
private ViewPager mPager; private SlidingTabLayout mTabs;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ...
mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager())); mTabs = (SlidingTabLayout) findViewById(R.id.tabs); mTabs.setViewPager(mPager);
...
}
class MyPagerAdapter extends FragmentPagerAdapter {
String[] tabs = new String[] { "待办事项", "番茄闹钟",
};
public MyPagerAdapter(FragmentManager fm) { super(fm); }
@Override public Fragment getItem(int i) { MyFragment myFragment = MyFragment.getInstance(i); return myFragment; }
@Override public int getCount() { return 2; }
@Override public CharSequence getPageTitle(int position) { return tabs[position]; } }
public static class MyFragment extends Fragment { private TextView textView; public static MyFragment getInstance(int position){ MyFragment myFragment = new MyFragment(); Bundle args = new Bundle(); args.putInt("position", position); myFragment.setArguments(args); return myFragment; }
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View layout = inflater.inflate(R.layout.fragment_my, container, false); textView = (TextView) layout.findViewById(R.id.position); Bundle bundle = getArguments(); if (bundle!= null){ textView.setText("The page Selected is "+ bundle.getInt("position")); } return layout; } }
}
|
Fragment的布局文件只是随便弄了个TextView。
效果
有人可能发现TAB没有适应屏幕,怎么实现呢,看StackOverFlow这里,有好几种实现方法,这里就不说了。