Android:使用ViewPager实现左右滑动切换图片(图上有点点)
在以下实例的基础上加上点点
Android:使用ViewPager实现左右滑动切换图片 (简单版)
效果预览:
因为要把点点放图片上,所以修改布局为相对布局:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <!-- 切换卡 --> <android.support.v4.view.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="wrap_content" > </android.support.v4.view.ViewPager> <!-- 点点 --> <LinearLayout android:id="@+id/viewGroup" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_marginBottom="40dp" android:gravity="center_horizontal" android:orientation="horizontal" > </LinearLayout> </RelativeLayout>
程序新增:
private ImageView imageView; private ImageView[] imageViews; //包裹点点的LinearLayout private ViewGroup group;
group = (ViewGroup)findViewById(R.id.viewGroup); //有多少张图就有多少个点点 imageViews = new ImageView[pageview.size()]; for(int i =0;i<pageview.size();i++){ imageView = new ImageView(MainActivity.this); imageView.setLayoutParams(new LayoutParams(20,20)); imageView.setPadding(20, 0, 20, 0); imageViews[i] = imageView; //默认第一张图显示为选中状态 if (i == 0) { imageViews[i].setBackgroundResource(R.drawable.page_indicator_focused); } else { imageViews[i].setBackgroundResource(R.drawable.page_indicator_unfocused); } group.addView(imageViews[i]); } //pageView监听器 class GuidePageChangeListener implements OnPageChangeListener{ @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override //如果切换了,就把当前的点点设置为选中背景,其他设置未选中背景 public void onPageSelected(int arg0) { // TODO Auto-generated method stub for(int i=0;i<imageViews.length;i++){ imageViews[arg0].setBackgroundResource(R.drawable.page_indicator_focused); if (arg0 != i) { imageViews[i].setBackgroundResource(R.drawable.page_indicator_unfocused); } } } } //绑定监听事件 viewPager.setOnPageChangeListener(new GuidePageChangeListener());
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。