ViewPager无限轮播+手动滑动+AsyncTask异步交互机制实例

我们来讲一个Viewpager无线轮播的实例,这个实例中用到了手动滑动,以及AsyncTask异步交互机制

首先是自动轮播匹配的小圆点的文件,放在drawable中,我们为选中的小圆点文件取名为dot_focus

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <corners android:radius="8dp"/>
    <solid android:color="#59b536"/>

</shape>

未选中状态小圆点文件 dot_normal

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

<corners android:radius="8dp"/>
    <solid android:color="#c2c2c2"/>
</shape>

接下来是布局

主页面布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="160dp" >

        <android.support.v4.view.ViewPager
            android:id="@+id/main_vp"
            android:layout_width="match_parent"
            android:layout_height="160dp" />

        <LinearLayout
            android:id="@+id/main_dots_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:layout_alignBottom="@id/main_vp"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>
    <TableRow 
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal"
        android:layout_marginTop="3dp"
        >
        <Button 
            android:id="@+id/main_bt_one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#666666"
            android:layout_weight="1"
            android:text="默认"
            />
        <View 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#cccccc"
            />
        <Button 
            android:id="@+id/main_bt_two"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#eaeaea"
            android:layout_weight="1"
            android:text="销量"
            />
        <View 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#cccccc"
            />
        <Button 
            android:id="@+id/main_bt_three"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#eaeaea"
            android:layout_weight="1"
            android:text="信誉"
            />
        <View 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#cccccc"
            />
        <Button 
            android:id="@+id/main_bt_four"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#eaeaea"
            android:layout_weight="1"
            android:text="价格"
            />
        <View 
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#cccccc"
            />
    </TableRow>
    <View 
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#cccccc"
        />
    <ListView 
        android:id="@+id/main_lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</LinearLayout>

listview的信息匹配页面 main_lv_item

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="120dp"
        android:gravity="center_vertical"
        android:background="#fff"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/main_lv_item_iv"
            android:layout_width="100dp"
            android:layout_height="120dp"
            android:src="@drawable/ic_launcher" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_marginLeft="5dp"
            android:orientation="vertical" >
            <TextView 
                android:id="@+id/main_lv_item_tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textSize="16sp"
                android:text="标题"
                />
            <TextView 
                android:id="@+id/main_lv_item_tv_brand"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"

                android:textSize="16sp"
                android:text="品牌"
                />
            <TextView 
                android:id="@+id/main_lv_item_tv_xiao"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:textSize="16sp"
                android:text="销量"
                />
            <RelativeLayout 
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                >
            <TextView 
                android:id="@+id/main_lv_item_tv_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#f00"
                android:textSize="14sp"
                android:text="价格"
                />

            <TextView
                android:id="@+id/main_lv_item_tv_good"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:layout_marginRight="14dp"
                android:text="好评"
                android:textSize="14sp" />

            </RelativeLayout>
        </LinearLayout>
    </TableRow>
    <View 
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#ccc"
        />

</LinearLayout>

我们这里单独写一个imageloader工具类 ImageLoadUtils,存放加载图片的方法

public class ImageLoadUtils {

    /*
     * 初始化ImageLoad配置信息 
     * (注意在application中初始化这样 就会保证程序一运行就会初始化配置)
     */

    public static void initConfiguation(Context context){
        //获取配置对象
        Builder configuation = new ImageLoaderConfiguration.Builder(context);
        //设置内存的缓存的图片大小
        configuation.memoryCacheExtraOptions(400, 800)
        //设置缓存进磁盘的图片大小
        .diskCacheExtraOptions(400, 800, null)
        .writeDebugLogs();

        //获取ImageLoader实例初始化环境信息
        ImageLoader.getInstance().init(configuation.build());
    }

    /*
     * 初始化视图选项
     */

    public static DisplayImageOptions initOptions(){
        DisplayImageOptions options = new DisplayImageOptions.Builder()
        //图片加载是显示的图片
        .showImageOnLoading(R.drawable.ic_launcher)
        //图片加载失败时显示的图片
        .showImageOnFail(R.drawable.ic_launcher)
        //是否缓存进内存
        .cacheInMemory(true)
        //是否缓存进sd卡
        .cacheOnDisk(true)
        .build();
        return options;
    }
}

写一个MyApplication第三方实现类

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化ImageLoader并传入全局上下文
        ImageLoadUtils.initConfiguation(getApplicationContext());
    }
}

我们接下来写一下listview适配器类MyAdapter和iewpager适配器类MyPagerAdapter

public class MyAdapter extends BaseAdapter{

    private  Context context;
    private DisplayImageOptions options;
    private List<MyItem> list;

    public MyAdapter(Context context,DisplayImageOptions options, List<MyItem> list) {
        super();
        this.context = context;
        this.options = options;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null){
            convertView = View.inflate(context, R.layout.main_lv_item, null);
            holder = new ViewHolder();
            //找控件
            holder.iv = (ImageView) convertView.findViewById(R.id.main_lv_item_iv);
            holder.title = (TextView) convertView.findViewById(R.id.main_lv_item_tv_title);
            holder.brand = (TextView)convertView.findViewById(R.id.main_lv_item_tv_brand);
            holder.xiao = (TextView)convertView.findViewById(R.id.main_lv_item_tv_xiao);
            holder.price = (TextView)convertView.findViewById(R.id.main_lv_item_tv_price);
            holder.good = (TextView)convertView.findViewById(R.id.main_lv_item_tv_good);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        ImageLoader.getInstance().displayImage(list.get(position).img, holder.iv, options);
        holder.title.setText(list.get(position).title);
        holder.brand.setText("品牌:"+list.get(position).brand);
        holder.xiao.setText("销量:"+list.get(position).salesVolume);
        holder.price.setText("¥:"+list.get(position).price);
        holder.good.setText("好评:"+list.get(position).good);
        return convertView;
    }

    class ViewHolder{
        ImageView iv;
        TextView title;
        TextView brand;
        TextView xiao;
        TextView price;
        TextView good;

    }

}
public class MyAdapter extends BaseAdapter{

    private  Context context;
    private DisplayImageOptions options;
    private List<MyItem> list;

    public MyAdapter(Context context,DisplayImageOptions options, List<MyItem> list) {
        super();
        this.context = context;
        this.options = options;
        this.list = list;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = null;
        if(convertView == null){
            convertView = View.inflate(context, R.layout.main_lv_item, null);
            holder = new ViewHolder();
            //找控件
            holder.iv = (ImageView) convertView.findViewById(R.id.main_lv_item_iv);
            holder.title = (TextView) convertView.findViewById(R.id.main_lv_item_tv_title);
            holder.brand = (TextView)convertView.findViewById(R.id.main_lv_item_tv_brand);
            holder.xiao = (TextView)convertView.findViewById(R.id.main_lv_item_tv_xiao);
            holder.price = (TextView)convertView.findViewById(R.id.main_lv_item_tv_price);
            holder.good = (TextView)convertView.findViewById(R.id.main_lv_item_tv_good);
            convertView.setTag(holder);
        }else{
            holder = (ViewHolder) convertView.getTag();
        }

        ImageLoader.getInstance().displayImage(list.get(position).img, holder.iv, options);
        holder.title.setText(list.get(position).title);
        holder.brand.setText("品牌:"+list.get(position).brand);
        holder.xiao.setText("销量:"+list.get(position).salesVolume);
        holder.price.setText("¥:"+list.get(position).price);
        holder.good.setText("好评:"+list.get(position).good);
        return convertView;
    }

    class ViewHolder{
        ImageView iv;
        TextView title;
        TextView brand;
        TextView xiao;
        TextView price;
        TextView good;

    }

}

接下来是我们通过这个网址解析到的json数据得到的bean类,这里应该写在工具类之前,原谅我这里疏忽了

public class Bean {

    public List<MyItem> item;
    public class MyItem{
        public String brand;
        public String good;
        public String img;
        public String salesVolume;
        public String price;
        public String title;
    }
}

最后使我们的MainActivity的编写

public class MainActivity extends Activity implements OnClickListener {

    private ViewPager main_vp;
    private Button main_bt_one;
    private Button main_bt_two;
    private Button main_bt_three;
    private Button main_bt_four;
    private ListView main_lv;
    private List<ImageView> dotsLlist;
    private LinearLayout dots_layout;
    private List<MyItem> vpimag = new ArrayList<MyItem>();
    private List<MyItem> listmr = new ArrayList<MyItem>();
    private List<MyItem> listxl = new ArrayList<MyItem>();
    private List<MyItem> listxy = new ArrayList<MyItem>();
    private List<MyItem> listjg = new ArrayList<MyItem>();
    private DisplayImageOptions options;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                int currentItem = main_vp.getCurrentItem();
                currentItem++;
                main_vp.setCurrentItem(currentItem);
                handler.sendEmptyMessageDelayed(1, 3000);
            }
        };
    };
    private MyAdapter adapter;
    private Button[] bts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //请求去掉窗口title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        // 初始化ImageImageLoader
        options = ImageLoadUtils.initOptions();
        // 找控件
        findComp();
        // 初始化小圆点
        initDots();
        // 执行异步请求
        MyAsyncTask task = new MyAsyncTask();
        task.execute("http://172.17.29.120/localuser/ljy/shoptest/commodity.json");
    }

    /*
     * 初始化小圆点的方法
     */
    private void initDots() {
        // 创建存储小圆点控件的集合
        dotsLlist = new ArrayList<ImageView>();
        // 在存储集合之前需要清除信息
        dotsLlist.clear();
        dots_layout.removeAllViews();
        for (int i = 0; i < 3; i++) {
            ImageView img = new ImageView(this);
            if (i == 0) {
                img.setImageResource(R.drawable.dots_focus);
            } else {
                img.setImageResource(R.drawable.dots_normal);
            }
            dotsLlist.add(img);
            LayoutParams params = new LayoutParams(16, 16);
            params.setMargins(8, 0, 8, 0);
            dots_layout.addView(img, params);
        }
    }

    /*
     * 所需控件
     */
    private void findComp() {
        main_vp = (ViewPager) findViewById(R.id.main_vp);
        dots_layout = (LinearLayout) findViewById(R.id.main_dots_layout);
        main_bt_one = (Button) findViewById(R.id.main_bt_one);
        main_bt_two = (Button) findViewById(R.id.main_bt_two);
        main_bt_three = (Button) findViewById(R.id.main_bt_three);
        main_bt_four = (Button) findViewById(R.id.main_bt_four);
        main_lv = (ListView) findViewById(R.id.main_lv);

        bts = new Button[] {main_bt_one,main_bt_two,main_bt_three,main_bt_four};
        // 设置四个按钮的监听并实现onClickListener接口
        main_bt_one.setOnClickListener(this);
        main_bt_two.setOnClickListener(this);
        main_bt_three.setOnClickListener(this);
        main_bt_four.setOnClickListener(this);
    }

    // 创建异步请求列
    class MyAsyncTask extends AsyncTask<String, Void, Bean[]> {

        @Override
        protected Bean[] doInBackground(String... params) {
            Bean[] bean = getNetData(params[0]);
            return bean;
        }

        @Override
        protected void onPostExecute(Bean[] result) {
            super.onPostExecute(result);
            // 设置数据的分配
            setData(result);
        }

        /*
         * 数据分配与设置适配器器的方法
         */
        private void setData(Bean[] result) {
            // 清除集合数据
            vpimag.clear();
            listjg.clear();
            listmr.clear();
            listxl.clear();
            listxy.clear();
            // 获取对应数据
            List<MyItem> img = result[0].item;
            List<MyItem> mr = result[1].item;
            List<MyItem> xl = result[2].item;
            List<MyItem> xy = result[3].item;
            List<MyItem> jg = result[4].item;
            // 将解析的数据存储到对应成员集和
            vpimag = img;
            listmr = mr;
            listxl = xl;
            listxy = xy;
            listjg = jg;
            // 为viewpager设置适配器
            MyPagerAdapter myPagerAdapter = new MyPagerAdapter(
                    MainActivity.this, vpimag, options);
            main_vp.setAdapter(myPagerAdapter);

            // 为ListView设置适配器
            setListAdapter(listmr);

            // 设置viewpager的监听
            setpagerlistener();
            handler.sendEmptyMessageDelayed(1, 3000);
        }

        /*
         * viewpager的监听方法
         */
        private void setpagerlistener() {
            main_vp.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    for (int i = 0; i < dotsLlist.size(); i++) {
                        if (i == arg0 % dotsLlist.size()) {
                            dotsLlist.get(i).setImageResource(
                                    R.drawable.dots_focus);
                        } else {
                            dotsLlist.get(i).setImageResource(
                                    R.drawable.dots_normal);
                        }
                    }
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });
        }

    }

    // 创建重网络获取数据的方法
    public Bean[] getNetData(String path) {
        try {
            HttpClient client = new DefaultHttpClient();
            // 执行请求
            HttpResponse response = client.execute(new HttpGet(path));
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                InputStream in = response.getEntity().getContent();
                int len = 0;
                byte[] b = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((len = in.read(b)) != -1) {
                    baos.write(b, 0, len);
                }
                String json = baos.toString("GBK");
                // Log.i("HOME", "json:"+json);
                Gson gson = new Gson();
                Bean[] bean = gson.fromJson(json, Bean[].class);
                return bean;
            }else{
                Toast.makeText(MainActivity.this, "服务器连接失败!", 0).show();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 在这里创建适配器方法供按钮调用
     */
    public void setListAdapter(List<MyItem> item) {
        adapter = new MyAdapter(MainActivity.this, options, item);
        main_lv.setAdapter(adapter);
    }

    /*
     * 改变按钮北京的按钮
     * 其中颜色在values文件的styles中配置
     */
    public void updateColor(int arg){
        for (int i = 0; i < bts.length; i++) {
            if(i == arg){
                bts[i].setBackgroundResource(R.color.bt_focus);
            }else{
                bts[i].setBackgroundResource(R.color.bt_normal);
            }
        }
    }

    // 重写按钮的点击方法
    @Override
    public void onClick(View v) {
        // 获取点击按钮的id
        int id = v.getId();
        switch (id) {
        case R.id.main_bt_one:
            setListAdapter(listmr);
            updateColor(0);
            break;

        case R.id.main_bt_two:
            updateColor(1);
            setListAdapter(listxl);
            break;

        case R.id.main_bt_three:
            updateColor(2);
            setListAdapter(listxy);
            break;

        case R.id.main_bt_four:
            updateColor(3);
            setListAdapter(listjg);
            break;
        }
    }

}

以上所有就是我的关于viewpager的无限轮播的简单实例,希望可以帮到大家

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kd953163660/article/details/51477141
文章标签: asynctask viewpager
个人分类: Android代码范
上一篇学院Logo展示+GridView
下一篇ViewPager无限轮播+自定义小圆点+ListView展示
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭