关闭

ViewPager无限轮播+自定义小圆点+ListView展示

标签: androidviewpager
329人阅读 评论(0) 收藏 举报
分类:

今天,我们来讲一个关于ViewPager无限轮播+自定义小圆点+ListView展示的简单的小案例,其中所得数据源自于这个网址

http://172.17.29.120/localuser/ljy/shoptest/commodity.json

接下来就按照我们代码流程,来详细讲解一下

第一步 写布局文件

首先是主页面布局

<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/vp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >
        </android.support.v4.view.ViewPager>

        <LinearLayout
            android:id="@+id/main_dots_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/vp"
            android:gravity="center_horizontal"
            android:orientation="horizontal" >
        </LinearLayout>
    </RelativeLayout>

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="3dp"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/main_bt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#666666"
            android:text="默认" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#eaeaea" />

        <Button
            android:id="@+id/main_bt2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#666666"
            android:text="销量" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#eaeaea" />

        <Button
            android:id="@+id/main_bt3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#666666"
            android:text="信誉" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#eaeaea" />
        <Button
            android:id="@+id/main_bt4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:background="#666666"
            android:text="价格" />

        <View
            android:layout_width="0.5dp"
            android:layout_height="match_parent"
            android:background="#eaeaea" />


    </TableRow>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.5dp"
        android:background="#cccccc" />

    <ListView
        android:id="@+id/lv_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

</LinearLayout>

然后是主页面布局中listview的适配目标布局 lv_item.xml

<?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="140dp"
        android:background="#fff"
        android:gravity="center_vertical"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/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/tv_itme_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="标题"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/tv_itme_brand"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="品牌"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/tv_itme_sale"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="5dp"
                android:text="销量"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/tv_item_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="价格"
                android:textColor="#f00"
                android:textSize="14sp" />

            <TextView
                android:id="@+id/tv_item_appraise"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="好评"
                android:textColor="#f00"
                android:textSize="14sp" />
        </LinearLayout>
    </TableRow>

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

</LinearLayout>

接下来我们创建一个drawable 文件夹,存放我们会用到的小圆点的自定义xml文件 dots_focus.xml 和dots_normal.xml 文件,这个文件中用到的是shape,只要给color属性不同的赋值就可以了,能够区别小圆点的不同状态就可

<?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>

通过请求数据的网址,我们得到数据,用HiJson编辑器格式化json串,得到数据分层,由此创建实体类

public class Result {
    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;
    }
}

因为要导入图片,所以我们使用Universal—imageloader来做,首先导入相关的jar包,也可以在开始就导入 这里我们导入 universal—imageloader 和gson包,也可以再导入xutils备用,然后建立一个ImageloaderUtils类

public class ImageLoaderUtils {

    /*
     * 初始化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类,来初始化Imageloader

public class MyApplication extends Application {

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

}

这里要记得,MyApplication类写了以后,要去AndroidManifest.xml配置一下
android:name=”com.bwie.uu.application.MyApplication”

接下来,写一下适配器类,这里有两个适配器类

public class MyPagerAdapter extends PagerAdapter {

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

    public MyPagerAdapter(Context context, List<MyItem> item,
            DisplayImageOptions options) {
        super();
        this.context = context;
        this.item = item;
        this.options = options;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return Integer.MAX_VALUE;
    }
    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
        // TODO Auto-generated method stub
        return arg0==arg1;
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView image=new ImageView(context);
        ImageLoader.getInstance().displayImage(item.get(position%item.size()).img, image, options);
        container.addView(image);
        return image;
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
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() {
        return list.size();
    }
    @Override
    public Object getItem(int arg0) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;  
        if (convertView==null) {
            convertView=View.inflate(context, R.layout.lv_item, null);
            viewHolder=new ViewHolder();
            viewHolder.iv=(ImageView) convertView.findViewById(R.id.lv_item_iv);
            viewHolder.title=(TextView) convertView.findViewById(R.id.tv_itme_title);
            viewHolder.brand=(TextView) convertView.findViewById(R.id.tv_itme_brand);
            viewHolder.sale=(TextView) convertView.findViewById(R.id.tv_itme_sale);
            viewHolder.price=(TextView) convertView.findViewById(R.id.tv_item_price);
            viewHolder.appraise=(TextView) convertView.findViewById(R.id.tv_item_appraise);
            convertView.setTag(viewHolder);
        }else{
            viewHolder=(ViewHolder) convertView.getTag();
        }
    ImageLoader.getInstance().displayImage(list.get(position).img, viewHolder.iv,options);
        viewHolder.title.setText(list.get(position).title);
        viewHolder.brand.setText("品牌:"+list.get(position).brand);
        viewHolder.sale.setText("销量:"+list.get(position).salesVolume);
        viewHolder.price.setText("¥:"+list.get(position).price);
        viewHolder.appraise.setText("好评:"+list.get(position).good);

        return convertView;
    }
    class ViewHolder{
        ImageView iv;
        TextView title;
        TextView brand;
        TextView sale;
        TextView price;
        TextView appraise;
    }
}

最后是我们的MainActivity类

public class MainActivity extends Activity implements OnClickListener {

    private List<ImageView> dotsList;
    private DisplayImageOptions options;
    private ListView lv_main;
    private LinearLayout dots_layout;
    private Button main_bt2;
    private Button main_bt1;
    private Button main_bt3;
    private Button main_bt4;
    private ViewPager vp_main;
    private Button[] bts;

    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 MyAdapter adapter;

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 1) {
                int currentItem = vp_main.getCurrentItem();
                currentItem++;
                vp_main.setCurrentItem(currentItem);
                handler.sendEmptyMessageDelayed(1, 3000);
            }
        };
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        options = ImageLoaderUtils.initOptions();
        // 查找控件
        findComp();
        // 初始化小圆点
        initDots();
        // 执行异步请求
        MyAsyncTask task = new MyAsyncTask();
        task.execute("http://172.17.29.120/localuser/ljy/shoptest/commodity.json");
    }

    private void initDots() {
        dotsList = new ArrayList<ImageView>();
        // 存储集合前清除信息
        dotsList.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);
            } 
            dotsList.add(img);
            LayoutParams params = new LayoutParams(16, 16);
            params.setMargins(8, 0, 8, 0);
            dots_layout.addView(img, params);
        }
    }

    private void findComp() {
        lv_main = (ListView) findViewById(R.id.lv_main);
        dots_layout = (LinearLayout) findViewById(R.id.main_dots_layout);
        main_bt1 = (Button) findViewById(R.id.main_bt1);
        main_bt2 = (Button) findViewById(R.id.main_bt2);
        main_bt3 = (Button) findViewById(R.id.main_bt3);
        main_bt4 = (Button) findViewById(R.id.main_bt4);
        vp_main = (ViewPager) findViewById(R.id.vp);
        bts = new Button[] { main_bt1, main_bt2, main_bt3, main_bt4 };

        // 设置四个按钮的点击监听
        main_bt1.setOnClickListener(this);
        main_bt2.setOnClickListener(this);
        main_bt3.setOnClickListener(this);
        main_bt4.setOnClickListener(this);
    }

    class MyAsyncTask extends AsyncTask<String, Void, Result[]> {

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

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

        private void setData(Result[] 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);
            vp_main.setAdapter(myPagerAdapter);

            setListAdapter(listmr);
            setPagerlistener();
            handler.sendEmptyMessageDelayed(1, 3000);

        }

        private void setPagerlistener() {
            vp_main.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    for (int i = 0; i < dotsList.size(); i++) {
                        if (i == arg0 % dotsList.size()) {
                            dotsList.get(i).setImageResource(
                                    R.drawable.dots_focus);
                        } else {
                            dotsList.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 Result[] 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();
                Result[] bean = gson.fromJson(json, Result[].class);
                return bean;
            } else {
                Toast.makeText(MainActivity.this, "服务器连接失败!", 0).show();
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public void setListAdapter(List<MyItem> item) {
        adapter = new MyAdapter(MainActivity.this, options, item);
        lv_main.setAdapter(adapter);
    }

    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_bt1:
            setListAdapter(listmr);
            updateColor(0);
            break;

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

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

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

好了,这就是一个完整的请求网络数据,使用ViewPager无限轮播+自定义小圆点+ListView展示的小范例,最后提醒下,项目要记得配置Internet权限哦

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3914次
    • 积分:201
    • 等级:
    • 排名:千里之外
    • 原创:15篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论