今天又看到了廣告輪播圖的效果匪凡,自己也就寫下來,作為一個筆記吧掘猿,俗話說病游,好記性不如爛筆頭,也可以供大家參考一下稠通,如果有錯誤請大家指出來衬衬,一起學(xué)習(xí)交流。
我個人歸納了一下實現(xiàn)輪播效果有以下幾個步驟:
一改橘、給ViewPager準(zhǔn)備好數(shù)據(jù)源
二滋尉、ViewPager設(shè)置Adapter
三、實現(xiàn)ViewPager自動輪播
四飞主、ViewPager設(shè)置OnPageChangeListener
五狮惜、設(shè)置輪播圖的觸摸事件和點擊事件
六、滑動事件和OnPageChangeListener 他們之前的沖突
OK碌识,接下來我們實現(xiàn)第一步
一碾篡、給ViewPager準(zhǔn)備好數(shù)據(jù)源
//這里的圖片和文字大家可以自行準(zhǔn)備
//圖片就是輪播的圖片
private int images[]={R.drawable.a,R.drawable.b,R.drawable.c,R.drawable.d,R.drawable.e};
//這個輪播圖下面的文字
private String titles[] = {"計算機網(wǎng)絡(luò)","C程序教程","軟件項目管理","JavaScript基礎(chǔ)教程","Android開發(fā)藝術(shù)探索"};
for (int i = 0; i < images.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(images[i]);
imageViews.add(imageView);
ImageView point = new ImageView(this);
//這里是將dp轉(zhuǎn)化為像素,以便更好的適應(yīng)各種屏幕
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DisplayUtils.dp2px(this, 8), DisplayUtils.dp2px(this, 8));
//這個是文字下面的點(被選中的為紅色)筏餐,這個可以叫美工
//做好圖片,這里我就沒有圖片开泽,使用的選擇器,代碼我后面也會貼出
point.setBackgroundResource(R.drawable.point_selector);
if (i == 0) {
point.setEnabled(true); //顯示紅色
} else {
point.setEnabled(false);//顯示灰色
lp.leftMargin = DisplayUtils.dp2px(this, 8);
}
point.setLayoutParams(lp);
ll_point.addView(point);
}
數(shù)據(jù)準(zhǔn)備好了 讓我們來實現(xiàn)第二步給ViewPager設(shè)置Adapter
mViewPager.setAdapter(new MyPagerAdapter());
class MyPagerAdapter extends PagerAdapter {
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = imageViews.get(position);
container.addView(imageView);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
@Override
public int getCount() {
return imageViews.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
ok ,也就是這樣的簡單魁瞪,當(dāng)然你也可以使用匿名內(nèi)部類穆律,這個我覺得看個人的喜歡就好,然后我們接下來我們來實現(xiàn)第三步导俘,圖片的無限自動輪播峦耘,其實很簡單,使用Handler旅薄,
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int item = mViewPager.getCurrentItem() + 1;
mViewPager.setCurrentItem(item);
mHandler.sendEmptyMessageDelayed(0, 3000);
}
};
只要在MyPagerAdapter 改幾行代碼就可以了贡歧,改一下getCount()方法
@Override
public int getCount() {
return Integer.MAX_VALUE;
}
和instantiateItem(ViewGroup container,int positon)方法
@Override
public Object instantiateItem(ViewGroup container, int position) {
//求余
int relPosition = position % images.length;
ImageView imageView = imageViews.get(relPosition);
container.addView(imageView);
return imageView;
}
接下來實現(xiàn)第四步,給ViewPager設(shè)置OnPageChangeListener
class MyOnPagerChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int relPosition = position % images.length;
mTitle.setText(titles[relPosition]);
ll_point.getChildAt(prePosition).setEnabled(false);//上一個設(shè)置為灰色
ll_point.getChildAt(relPosition).setEnabled(true);//當(dāng)前的設(shè)置為紅色
prePosition = relPosition;
}
/**
* 靜止--> 滑動
* 滑動-->靜止
* 靜止-->拖拽
*
* @param state
*/
@Override
public void onPageScrollStateChanged(int state) {}
}
我們有時候會有這樣的需求赋秀,就是當(dāng)我們手指點在圖片上的時候利朵,圖片停止自動輪播,當(dāng)我們手放開的時候猎莲,圖片又自動輪播起來绍弟,這個其實也很簡單,只要改一下instantiateItem(ViewGroup container, int position) 方法就ok著洼,接下來我就實現(xiàn)以下這樣的效果
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = imageViews.get(position);
container.addView(imageView);
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
L.i("action down .. ");
mHandler.removeCallbacksAndMessages(null);//移除所有的消息
break;
case MotionEvent.ACTION_UP:
L.i("action up .. ");
mHandler.removeCallbacksAndMessages(null);//移除所有的消息
mHandler.sendEmptyMessageDelayed(0, 3000);
break;
}
return false;//若返回為true 則無法實現(xiàn)點擊事件
}
});
imageView.setTag(relPosition);//這樣可以拿到點擊的位置
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = (int) imageView.getTag();
Toast.makeText(MyBannerActivity.this, "you click the imageview position is :" + position, Toast.LENGTH_SHORT).show();
}
});
return imageView;
}
哈哈哈樟遣,終于完成了而叼,但是你會發(fā)現(xiàn),這個滑動事件和那個ontouch之間會有沖突豹悬,當(dāng)你點住輪播圖璧诵,往右(左)拖一定的距離路捧,然后你釋放,發(fā)現(xiàn)ACTION_UP效果并沒有實現(xiàn),圖片不會自動輪播了枷莉,這樣子用戶的體驗就不是很好了泞莉,接下來牧氮,我們來解決這個問題
這就是圖片輪播的最后一步,只要onPageScrollStateChanged(int state)這個方法就可以了去团,我們用一個boolean的值來判斷用戶是否拖拽,初始值為false.
private boolean isDragging = false;
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE && isDragging) {
isDragging = false;
mHandler.removeCallbacksAndMessages(null);
mHandler.sendEmptyMessageDelayed(0, 3000);
} else if (state == ViewPager.SCROLL_STATE_DRAGGING) {
isDragging = true;
mHandler.removeCallbacksAndMessages(null);
}
}
接下來我貼出完整的代碼
布局文件 activity_banner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/vp_banner"
android:layout_width="match_parent"
android:layout_height="180dp">
</android.support.v4.view.ViewPager>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="@id/vp_banner"
android:gravity="center"
android:background="#44000000"
>
<TextView
android:id="@+id/tv_title"
android:text="加勒比海盜5"
android:textColor="#ffffff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<LinearLayout
android:gravity="center"
android:id="@+id/ll_point"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</LinearLayout>
</RelativeLayout>
選擇器
point_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/point_nor"/>
<item android:state_enabled="true" android:drawable="@drawable/point_heightlight"/>
</selector>
point_nor.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<size android:height="8dp"
android:width="8dp"/>
<solid android:color="#44000000"/>
</shape>
point_heightlight.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<size android:height="8dp"
android:width="8dp"/>
<solid android:color="#FF0000"/>
</shape>
MyBannerActivity.java
/**
* author WuGuofei on 2017/6/4.
*/
public class MyBannerActivity extends AppCompatActivity {
private ViewPager mViewPager;
private LinearLayout ll_point;
private TextView mTitle;
private List<ImageView> imageViews;
private int images[] = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e};
private String titles[] = {"計算機網(wǎng)絡(luò)", "C程序教程", "軟件項目管理", "JavaScript基礎(chǔ)教程", "Android開發(fā)藝術(shù)探索"};
private int prePosition = 0;
private boolean isDragging = false;//是否拖拽
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int item = mViewPager.getCurrentItem() + 1;
mViewPager.setCurrentItem(item);
mHandler.sendEmptyMessageDelayed(0, 3000);
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banner);
mViewPager = (ViewPager) findViewById(R.id.vp_banner);
ll_point = (LinearLayout) findViewById(R.id.ll_point);
mTitle = (TextView) findViewById(R.id.tv_title);
imageViews = new ArrayList<>();
for (int i = 0; i < images.length; i++) {
ImageView imageView = new ImageView(this);
imageView.setBackgroundResource(images[i]);
imageViews.add(imageView);
ImageView point = new ImageView(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(DisplayUtils.dp2px(this, 8), DisplayUtils.dp2px(this, 8));
point.setBackgroundResource(R.drawable.point_selector);
if (i == 0) {
point.setEnabled(true); //顯示紅色
} else {
point.setEnabled(false);//顯示灰色
lp.leftMargin = 16;
}
point.setLayoutParams(lp);
ll_point.addView(point);
}
mViewPager.setAdapter(new MyPagerAdapter());
mViewPager.addOnPageChangeListener(new MyOnPagerChangeListener());
int item = Integer.MAX_VALUE / 2 - Integer.MAX_VALUE / 2 % images.length;//為了是images的倍數(shù),在中間的位置
mViewPager.setCurrentItem(item);
mTitle.setText(titles[prePosition]);
//發(fā)消息 實現(xiàn)自動輪播
mHandler.sendEmptyMessageDelayed(0, 3000);
}
class MyOnPagerChangeListener implements ViewPager.OnPageChangeListener {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
int relPosition = position % images.length;
mTitle.setText(titles[relPosition]);
ll_point.getChildAt(prePosition).setEnabled(false);//上一個設(shè)置為灰色
ll_point.getChildAt(relPosition).setEnabled(true);//當(dāng)前的設(shè)置為紅色
prePosition = relPosition;
}
/**
* 靜止--> 滑動
* 滑動-->靜止
* 靜止-->拖拽
*
* @param state
*/
@Override
public void onPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE && isDragging) {
isDragging = false;
mHandler.removeCallbacksAndMessages(null);
mHandler.sendEmptyMessageDelayed(0, 3000);
} else if (state == ViewPager.SCROLL_STATE_DRAGGING) {
isDragging = true;
mHandler.removeCallbacksAndMessages(null);
} else if (state == ViewPager.SCROLL_STATE_SETTLING) {
}
}
}
class MyPagerAdapter extends PagerAdapter {
@Override
public Object instantiateItem(ViewGroup container, int position) {
int relPosition = position % images.length;
final ImageView imageView = imageViews.get(relPosition);
container.addView(imageView);
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
L.i("action down .. ");
mHandler.removeCallbacksAndMessages(null);//移除所有的消息
break;
case MotionEvent.ACTION_UP:
L.i("action up .. ");
mHandler.removeCallbacksAndMessages(null);//移除所有的消息
mHandler.sendEmptyMessageDelayed(0, 3000);
break;
}
return false;//若返回為true 則無法實現(xiàn)點擊事件
}
});
imageView.setTag(relPosition);//這樣可以拿到點擊的位置
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int position = (int) imageView.getTag();
Toast.makeText(MyBannerActivity.this, "you click the imageview position is :" + position, Toast.LENGTH_SHORT).show();
}
});
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
// super.destroyItem(container, position, object);
container.removeView((View) object);
}
@Override
public int getCount() {
//return imageViews.size();
return Integer.MAX_VALUE;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
步驟就寫到這里了适刀,今天第一次寫這個文章秤朗,寫的條理不夠好,望大家多多包涵笔喉,以后能力提升取视,一定對文章做出修改