android 輪播圖 使用banner依賴實現
阿新 • • 發佈:2018-12-22
首先引入輪播圖的一個依賴
compile 'com.hejunlin.superindicatorlibray:superindicatorlibray:1.0.3'
這是這個依賴作者github上的地址https://github.com/hejunlin2013/SuperIndicator
下面是佈局檔案
幀佈局中放置指示針
<com.hejunlin.superindicatorlibray.LoopViewPager android:id="@+id/looperviewpager" android:layout_width="match_parent" android:layout_height="match_parent"/> <FrameLayout android:layout_width="match_parent" android:layout_height="@dimen/dimen_48dp" android:layout_gravity="bottom"> <com.hejunlin.superindicatorlibray.CircleIndicator android:id="@+id/indicator" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="horizontal"/> </FrameLayout>
每一個LoopViewPager的佈局
我命名為home_pic_item
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_guide" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/iv_img" android:layout_width="match_parent" android:layout_height="match_parent" android:scaleType="fitXY" /> <!--layout_gravity 父佈局的位置--> <!--gravity 自己(本身)佈局的位置--> <TextView android:id="@+id/tv_dec" android:layout_width="match_parent" android:layout_height="@dimen/dimen_40dp" android:textSize="@dimen/dimen_28sp" android:layout_gravity="bottom|left" android:layout_marginLeft="@dimen/dimen_6dp" android:textColor="@color/white" /> </FrameLayout>
下面是初始化程式碼:
LoopViewPager viewPager = bindViewId(R.id.looperviewpager); CircleIndicator indicator = bindViewId(R.id.indicator); viewPager.setAdapter(new HomePicAdapter(getActivity())); viewPager.setLooperPic(true);//5s自動輪播 indicator.setViewPager(viewPager); //indicator需要知道viewpager
最後介面卡中的程式碼
public class HomePicAdapter extends PagerAdapter {
private Context mContext;
//文字
private int[] mDes = new int[] {
R.string.a_name,
R.string.b_name,
R.string.c_name,
R.string.d_name,
R.string.e_name,
};
//圖片
private int[] mImg = new int[] {
R.drawable.a,
R.drawable.b,
R.drawable.c,
R.drawable.d,
R.drawable.e,
};
public HomePicAdapter(Activity activity) {
mContext = activity;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View view = LayoutInflater.from(mContext).inflate(R.layout.home_pic_item, null);
TextView textView = (TextView) view.findViewById(R.id.tv_dec);
ImageView imageView = (ImageView) view.findViewById(R.id.iv_img);
textView.setText(mDes[position]);
imageView.setImageResource(mImg[position]);
container.addView(view);
return view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
@Override
public int getCount() {
return 5;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
效果圖: