天天看點

Android網絡圖檔實作圖檔輪播

今天看到洪洋也就是翔哥大神的視訊和部落格之後,深的體會,翔哥的位址:http://blog.csdn.net/lmj623565791/article/details/42160391

看了他的部落格之後就會很清晰實作一個圖檔輪播如何實作,首先得自定義一個訓示器ViewPagerIndicator繼承LinearLayout,然後自定義View的兩個構造方法

public ViewPagerIndicator(Context context) {
    this(context,null);
}

public ViewPagerIndicator(Context context, AttributeSet attrs) {
    super(context, attrs);
   
}      
之後activity_main布局如下:      
<?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="180dp"
    android:background="@android:color/holo_blue_bright"
    >
    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        ></android.support.v4.view.ViewPager>

<com.confress.customimageslider.ViewPagerIndicator
    android:id="@+id/indicator"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginRight="5dp"
    android:layout_marginBottom="5dp"
    android:orientation="horizontal">
</com.confress.customimageslider.ViewPagerIndicator>


</RelativeLayout>
      
預期實作效果如下:      
Android網絡圖檔實作圖檔輪播
首先實作的就是Viewpager和訓示器的滑動顯示效果,那麼第一步就是建立ViewPager的Fragment,Fragment代碼如下:      
package com.confress.customimageslider;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;

/**
 * Created by admin on 2016/3/22.
 */
public class VpSimpleFragment extends Fragment {
    private String mImagePath;
    public  static final  String BUNDLE_IMAGEPATH="image_path";


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       Bundle bundle=getArguments();
        if (bundle!=null){
            mImagePath=bundle.getString(BUNDLE_IMAGEPATH);
        }
        View root=inflater.inflate(R.layout.fragment_image,container,false);
        ImageView image= (ImageView) root.findViewById(R.id.image);
        Glide.with(getActivity()).load(mImagePath).into(image);
        return root;
    }

    public  static  VpSimpleFragment newInstance(String path){
        Bundle bundle=new Bundle();
        bundle.putString(BUNDLE_IMAGEPATH, path);
        VpSimpleFragment fragment=new VpSimpleFragment();
        fragment.setArguments(bundle);
        return  fragment;
    }
}
      
其中fragment_image代碼更加簡單:      
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:scaleType="fitXY">
    </ImageView>      
上面代碼很簡單沒什麼好說的,MainActivity首先需要圖檔的位址,VpSimpleFragment的List集合,如下      
private List<String> mImagePath= Arrays.asList(
        "http://img.taodiantong.cn/v55183/infoimg/2013-07/130720115322ky.jpg",
        "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
        "http://pic18.nipic.com/20111215/577405_080531548148_2.jpg",
        "http://pic15.nipic.com/20110722/2912365_092519919000_2.jpg",
        "http://pic.58pic.com/58pic/12/64/27/55U58PICrdX.jpg");
private  List<VpSimpleFragment> mContents=new ArrayList<>();
private FragmentPagerAdapter mAdpter;      
然後初始化資料,也就是mAdpter和mContents的List集合
private void initDatas() {
    for (String imagepath:mImagePath){
        VpSimpleFragment fragment = VpSimpleFragment.newInstance(imagepath);
        mContents.add(fragment);
    }
    mAdpter=new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return mContents.get(position);
        }

        @Override
        public int getCount() {
            return mContents.size();
        }
    };
}      
最後就viewpager.setAdapter(mAdpter);可以實作一個很簡單的類型與微信滑動頁面切換功能。但是這與我們預想得到的還是有很大出入,這時候就需要自定義和mViewpager與ViewPagerIndicator實作綁定功能。      
首先是資料源ImageUrl的綁定,通過設定一個setTabItemImagecator方法實作動态添加ImageUrl與點選事件響應      
public  void setTabItemImagecator(List<String> datas){
    if (datas!=null&&datas.size()>0){
        this.removeAllViews();
        this.mTabsImagePath=datas;
        for (String path:mTabsImagePath){
            addView(generateImageView());
        }
        // 設定item的click事件
        setItemClickEvent();
    }
}      
private View generateImageView() {
    ImageView imageView=new ImageView(getContext());
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            25,25);
    lp.setMargins(5,5,5,5);
    imageView.setImageResource(R.drawable.ic_focus_select);
    imageView.setLayoutParams(lp);
    return imageView;
}      
/**
 * 設定點選事件
 */
public void setItemClickEvent()
{
    int cCount = getChildCount();
    for (int i = 0; i < cCount; i++)
    {
        final int j = i;
        View view = getChildAt(i);
        view.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mViewPager.setCurrentItem(j);
            }
        });
    }
}      
之後設定一個mViewPager與訓示器圖檔切換綁定方法:      
/**
     * 對外的ViewPager的回調接口
     *
     * @author zhy
     *
     */
    public interface PageChangeListener
    {
        public void onPageScrolled(int position, float positionOffset,
                                   int positionOffsetPixels);

        public void onPageSelected(int position);

        public void onPageScrollStateChanged(int state);
    }

    // 對外的ViewPager的回調接口
    private PageChangeListener onPageChangeListener;

    // 對外的ViewPager的回調接口的設定
    public void setOnPageChangeListener(PageChangeListener pageChangeListener)
    {
        this.onPageChangeListener = pageChangeListener;
    }

    // 設定關聯的ViewPager
    public void setViewPager(final ViewPager mViewPager, final int pos)
    {
        this.mViewPager = mViewPager;

        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                // 設定字型顔色高亮
                resetImageViewColor();
                highLightImageView(position);

                // 回調
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageSelected(position);
                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
//                if (position==mTabsImagePath.size()-1){
//                    SystemClock.sleep(1000);
//                    mViewPager.setCurrentItem(0);
//                }
                mPosition = position;
                // 回調
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageScrolled(position,
                            positionOffset, positionOffsetPixels);
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // 回調
                if (onPageChangeListener != null) {
                    onPageChangeListener.onPageScrollStateChanged(state);
                }

            }
        });
        // 設定目前頁
        mViewPager.setCurrentItem(pos);
        // 高亮
        highLightImageView(pos);
    }

    /**
     * 高亮文本
     *
     * @param position
     */
    protected void highLightImageView(int position)
    {
        View view = getChildAt(position);
        if (view instanceof ImageView)
        {
            ((ImageView) view).setImageResource(R.drawable.ic_focus);
        }

    }

    /**
     * 重置文本顔色
     */
    private void resetImageViewColor()
    {
        for (int i = 0; i < getChildCount(); i++)
        {
            View view = getChildAt(i);
            if (view instanceof ImageView)
            {
                ((ImageView) view).setImageResource(R.drawable.ic_focus_select);
            }
        }
    }
      
最後在設定一個定時器功能實作每2秒自動切換圖檔:      
Timer timer = new Timer();
TimerTask task = new TimerTask() {

    @Override
    public void run() {
        // 需要做的事:發送消息
        Message message = new Message();
        message.what = mPosition+1;
        handler.sendMessage(message);
    }
};

Handler handler = new Handler() {
    public void handleMessage(Message msg) {
        mViewPager.setCurrentItem(msg.what%mTabsImagePath.size());
        super.handleMessage(msg);
    };
};      
timer.schedule(task, 1000, 2000); // 1s後執行task,經過1s再次執行
      
可能我說的不夠好,也不夠精彩,畢竟我是仿造翔哥的,看翔哥的視訊位址說的很清楚:http://www.imooc.com/video/11312      
最後附上代碼下載下傳位址:https://github.com/1036711153/CustomImagerSilder