仿微信(网易的界面)
第一步: AndroidManifest.xml 的配置
//定义了 一些样式
样式
选择器selector_tabtext.xml 和tab_indicator.xml
//selector_tabtext
//tab_indicator
第二步 :class MainActivity extends FragmentActivity
/** * Tab标题 */ private static final String[] TITLE = new String[] { "头条", "房产", "另一面" }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //ViewPager的adapter FragmentPagerAdapter adapter = new TabPageIndicatorAdapter(getSupportFragmentManager()); ViewPager pager = (ViewPager)findViewById(R.id.pager); pager.setAdapter(adapter); //viewpage设置值 //实例化TabPageIndicator然后设置ViewPager与之关联 TabPageIndicator indicator = (TabPageIndicator)findViewById(R.id.indicator); indicator.setViewPager(pager); //下标 绑定 page //如果我们要对ViewPager设置监听,用indicator设置就行了 indicator.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int arg0) { Toast.makeText(getApplicationContext(), TITLE[arg0], Toast.LENGTH_SHORT).show(); } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } /** * ViewPager适配器 * @author len * */ class TabPageIndicatorAdapter extends FragmentPagerAdapter { public TabPageIndicatorAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { //新建一个Fragment来展示ViewPager item的内容,并传递参数 Fragment fragment = new ItemFragment(); Bundle args = new Bundle(); args.putString("arg", TITLE[position]); fragment.setArguments(args); return fragment; } @Override public CharSequence getPageTitle(int position) { return TITLE[position%TITLE.length ]; // 取数组里面的值 最为title } @Override public int getCount() { return TITLE.length; } }
Fragment
public class ItemFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View contextView = inflater.inflate(R.layout.fragment_item, container, false); TextView mTextView = (TextView) contextView.findViewById(R.id.textview); //获取Activity传递过来的参数 Bundle mBundle = getArguments(); String title = mBundle.getString("arg"); mTextView.setText(title); return contextView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); }}