Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> [Android]最省內存的ViewPager添加小圓點指示器

[Android]最省內存的ViewPager添加小圓點指示器

編輯:關於Android編程

原理:

這個你可以用View疊加來實現,但是這個效果不太理想,1占內存,而移植起來不方便,需要找各種資源,所以采用自己繪制更好,方便,而且效率高。

解決方案:

package com.youtu.view;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;

public class ADView extends ViewPager {

	AdAdapter mAdAdapter;
	Context context;
	Paint paint;
	List> urls;

	public ADView(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		paint = new Paint();
		InitAdapter();
	}

	private void InitAdapter() {
		urls = new ArrayList>();
		mAdAdapter = new AdAdapter(context, urls);
		this.setAdapter(mAdAdapter);
	}

	public void setData(List> data) {
		urls.clear();
		for (int i = 0; i < data.size(); i++) {
			urls.add(data.get(i));
		}
		if(urls.size()>0){
			this.setVisibility(View.VISIBLE);
		}else{
			this.setVisibility(View.GONE);
		}
		mAdAdapter.notifyDataSetChanged();
	}

	@Override
	public void draw(Canvas canvas) {
		super.draw(canvas);
		drawCycle(canvas);
	}

	private void drawCycle(Canvas canvas) {
		canvas.save();
		canvas.translate(getScrollX(), getScrollY());
		int count = 0;
		if (this.getAdapter() != null) {
			count = this.getAdapter().getCount();
		}
		int select = getCurrentItem();
		float density = getContext().getResources().getDisplayMetrics().density;
		int itemWidth = (int) (11 * density);
		int itemHeight = itemWidth / 2;
		int x = (getWidth() - count * itemWidth)/2;
		int y = getHeight() - itemWidth;
		int minItemHeight = (int) ((float) itemHeight * 0.8F);
		paint.setAntiAlias(true);

		paint.setStyle(Style.FILL);
		for (int i = 0; i < count; i++) {
			if (select == i) {
				paint.setColor(0xFFbdbdbd);
				canvas.drawCircle(x + itemWidth * i + itemWidth / 2, y, minItemHeight, paint);
			} else {
				paint.setColor(0xFFe6e6e6);
				canvas.drawCircle(x + itemWidth * i + itemWidth / 2, y, minItemHeight, paint);
			}
		}
		canvas.restore();
	}

}


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved