Android Viewpager Fragme动态切换菜单_安卓左右滑动切换菜单例子
2014-10-13 13:33:34 By: shinyuu
今天分享一个Android Viewpager Fragme切换菜单的例子、类似于老版本的微信的切换效果
利用Viewpager+Fragment实现顶部选项卡、可以通过滑动、点击来进行Fragment页面切换
如需要添加页面或减少页面、修改PageSize即可——下方对应添加Fragment到管理器中
先来看一下运行效果吧、是可以左右滑动的、也可以点击的哈
初始化动画、这个就是页卡滑动时、下面的横线也滑动的效果、在这里需要计算一些数据
private void InitImageView() { imageView = (ImageView) findViewById(R.id.cursor); // 获取图片宽度 bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.tab_selected_bg).getWidth(); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); // 获取分辨率宽度 int screenW = dm.widthPixels; // 计算偏移量--(屏幕宽度/页卡总数-图片实际宽度)/2 offset = (screenW / pageSize - bmpW) / 2; // = 偏移量 Matrix matrix = new Matrix(); matrix.postTranslate(offset, 0); // 设置动画初始位置 imageView.setImageMatrix(matrix); }
头标点击监听
private class MyOnClickListener implements OnClickListener { private int index = 0; public MyOnClickListener(int i) { index = i; } public void onClick(View v) { switch (index) { case 0: voiceAnswer.setTextColor(selectedColor); healthPedia.setTextColor(unSelectedColor); pDected.setTextColor(unSelectedColor); break; case 1: healthPedia.setTextColor(selectedColor); voiceAnswer.setTextColor(unSelectedColor); pDected.setTextColor(unSelectedColor); break; case 2: pDected.setTextColor(selectedColor); voiceAnswer.setTextColor(unSelectedColor); healthPedia.setTextColor(unSelectedColor); break; } viewPager.setCurrentItem(index); } }
为选项卡绑定监听器
public class MyOnPageChangeListener implements OnPageChangeListener { // 页卡1 -> 页卡2 偏移量 int one = offset * 2 + bmpW; // 页卡1 -> 页卡3 偏移量 int two = one * 2; public void onPageScrollStateChanged(int index) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } public void onPageSelected(int index) { // 显然这个比较简洁,只有一行代码。 Animation animation = new TranslateAnimation(one * currIndex, one * index, 0, 0); currIndex = index; // True:图片停在动画结束位置 animation.setFillAfter(true); animation.setDuration(300); imageView.startAnimation(animation); switch (index) { case 0: voiceAnswer.setTextColor(selectedColor); healthPedia.setTextColor(unSelectedColor); pDected.setTextColor(unSelectedColor); break; case 1: healthPedia.setTextColor(selectedColor); voiceAnswer.setTextColor(unSelectedColor); pDected.setTextColor(unSelectedColor); break; case 2: pDected.setTextColor(selectedColor); voiceAnswer.setTextColor(unSelectedColor); healthPedia.setTextColor(unSelectedColor); break; } } }
核心代码都在上面了哈、源代码下载链接: http://dwtedx.com/download.html?bdkey=s/1i37mXqX 密码: ox5s
若资源对你有帮助、浏览后有很大收获、不妨小额打赏我一下、你的鼓励是维持我不断写博客最大动力
想获取DD博客最新代码、你可以扫描下方的二维码、关注DD博客微信公众号(ddblogs)
或者你也可以关注我的新浪微博、了解DD博客的最新动态:DD博客官方微博(dwtedx的微博)
如对资源有任何疑问或觉得仍然有很大的改善空间、可以对该博文进行评论、希望不吝赐教
为保证及时回复、可以使用博客留言板给我留言: DD博客留言板(dwtedx的留言板)
感谢你的访问、祝你生活愉快、工作顺心、欢迎常来逛逛