在我们写项目中经常会遇到这样的需求,首页有个能够自动滚动并循环播放的广告图。它能够显示小圆点,并且可以实现左右无限滑动。我们先看下效果图:
下面我们来看下具体是怎么实现的吧。
首先,先看看布局吧:
<?xml version="1.0" encoding="utf-8"?>
<com.bbjia.ui.widget.Ticker xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:duomi="http://schemas.android.com/apk/res/com.bbjia.bbting"
android:layout_width="match_parent"
android:layout_height="@dimen/dm_gallery_height" >
<com.bbjia.ui.widget.DMGallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/layout"
android:layout_width="fill_parent"
android:layout_height="11dip"
android:layout_alignParentBottom="true" >
<com.bbjia.ui.widget.DMSlidingIndicator
android:id="@+id/gallery_indicator"
android:layout_width="wrap_content"
android:layout_height="6.0dip"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
duomi:indicator_drawable="@drawable/indicator_search_guide"
duomi:indicator_margin="3dip" />
</RelativeLayout>
</com.bbjia.ui.widget.Ticker>
最外层的com.bbjjia.ui.widget.Ticker是个继承RelativeLayout的继承控件,拥有RelativeLayout的所有属性,大家可以把它看作RelativeLayout。然后com.bbjia.ui.widget.DMGallery是个继承Gallery的控件。布局里面的RelativeLayout以及它包裹的com.bbjia.ui.widget.DMSlidingIndicator就是大家看的效果图中的小圆点对应的布局。com.bbjia.ui.widget.DMSlidingIndicator里面有两个自定义的属性,duomi:indicator_drawable和duomi:indicator_margin。我们直接看代码:
<declare-styleable name="indicator">
<attr name="indicator_drawable" format="reference"></attr>
<attr name="indicator_margin" format="reference|dimension"></attr>
</declare-styleable>
name就是属性名,format是对应值的类型。reference是
参考某一资源的ID。dimension则是尺寸值。在代码中可以这样使用:
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.indicator);
Drawable d = a.getDrawable(R.styleable.indicator_indicator_drawable);
margin = (int) a.getDimension(R.styleable.indicator_indicator_margin, 0);
下面我们来看下Ticker具体代码是怎样实现的:
public class Ticker extends RelativeLayout implements ListCell,
OnItemSelectedListener, OnItemClickListener {
private DMGallery gallery;//放图片的控件
private DMSlidingIndicator galleryIndicator;//放小圆点的控件
private View layout;
private LayoutInflater mLayoutInflater;
private RTickerAdapter<TickerObj> adapter;//放图片对应的adapter
private int tickerHeight;//用来设置图片的高度(避免图片拉伸,影响效果)
private final static int TIME = 5 * 1000;//图片自动切换的时间
private Loopable mLoopable;//自定义的接口
/**
* 设置轮播
* @param loopable
*/
public void setLoopable(Loopable loopable) {
mLoopable = loopable;
if (gallery != null) {
gallery.setLoopable(loopable);//设置图片的轮播
}
}
public Ticker(Context context, AttributeSet attrs) {
super(context, attrs);
mLayoutInflater = LayoutInflater.from(context);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
this.gallery = (DMGallery) findViewById(R.id.gallery);
this.layout = findViewById(R.id.layout);
this.galleryIndicator = (DMSlidingIndicator) findViewById(R.id.gallery_indicator);
this.gallery.setOnItemSelectedListener(this);
this.gallery.setOnItemClickListener(this);
int baseWidth = getResources().getDisplayMetrics().wid