Android玉石短剑之GridView之精挑细选

传送门 ☞ Android兵器谱 ☞ 转载请注明 ☞ http://blog.csdn.net/leverage_1229


玉石短剑
        奔到大殿,陈家洛捡起三柄玉剑,每人手中拿了一把,低声道:“玉器可以辟邪。”这时脚步声已到殿外。。。阿里和其余勇士捉到了一个桑拉巴的手下,迫着他带路,攻进了神峰。在大殿上,他们的刀剑都被磁山收了去,桑拉巴的武士拿玉刀玉剑来杀他们。然而阿里和他的勇士学会了本事,虽然空手,仍是一个个的和他们一起战死。

        今天我们学习如何利用Android平台“玉石短剑”GridView来实现“九宫格”的图片效果,并提供对GridView中各张图片的单选和复选功能。采用“九宫格”展示图像的情景很常见,像电子相册、写真集、主屏桌面、功能菜单项等。下面给出该情景的案例:

一、案例技术要点

1.创建两个GridView控件分别用于展示支持单选和复选功能的“九宫格”图片。

2.为这两个GridView控件提供图片资源适配器ImageAdapter,使用isMultiSelect变量标示是单选还是复选模式

3.为GridView中各项设置监听OnItemClickListener,用于实时记录各张图片的选择状态。另外,单选状态需要记录上一次选中的图片位置。

// 记录各张图片的Id
private ArrayList<Integer> imageIds = new ArrayList<Integer>();
// 记录各张图片的选择状态
private HashMap<Integer, Boolean> imageStatues = new HashMap<Integer, Boolean>();

4.利用LayerDrawable类构建叠加图层,将标示勾选与否的图片置于显示各张图片的视图控件的左上方。

Drawable[] drawArr = new Drawable[2];
drawArr[0] = new BitmapDrawable(imageBmp);
drawArr[1] = new BitmapDrawable(selectedBmp);
LayerDrawable layerDrawable = new LayerDrawable(drawArr);
layerDrawable.setLayerInset(0, 0, 0, 0, 0);
layerDrawable.setLayerInset(1, 0, 0, 60, 60);

二、案例代码陈列

工程包目录

Android玉石短剑之GridView之精挑细选_第1张图片

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.lynn.gridview"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".GridViewMainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
strings.xml
<resources>

    <string name="app_name">Android单复选九宫格GridView</string>

</resources>
main.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"
    android:gravity="center" >

    <GridView
        android:id="@+id/radioGridView"
        android:layout_width="210dp"
        android:layout_height="210dp"
        android:gravity="center"
        android:numColumns="3" />

    <GridView
        android:id="@+id/checkGridView"
        android:layout_width="210dp"
        android:layout_height="210dp"
        android:gravity="center"
        android:numColumns="3" />

</LinearLayout>
ImageAdapter.java
package cn.lynn.gridview;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

public class ImageAdapter extends BaseAdapter {

    private Context context;
    // 记录各张图片的Id
    private ArrayList<Integer> imageIds = new ArrayList<Integer>();
    // 记录各张图片的选择状态
    private HashMap<Integer, Boolean> imageStatues = new HashMap<Integer, Boolean>();

    // 记录上一次选中的图片位置,-1表示未选中任何图片
    private int lastPosition = -1;

    // 表示当前适配器是否允许多选
    private boolean isMultiSelect;

    // 声明图片资源数组
    private int[] imageResIds = { R.drawable.item1, R.drawable.item2,
            R.drawable.item3, R.drawable.item4, R.drawable.item5,
            R.drawable.item6, R.drawable.item7, R.drawable.item8,
            R.drawable.item9 };

    public ImageAdapter(Context context, boolean isMultiSelect) {
        this.context = context;
        this.isMultiSelect = isMultiSelect;
        
        // 采集图片资源
        for (int i = 0; i < imageResIds.length; i++) {
            imageIds.add(imageResIds[i]);
        }
        for (int i = 0; i < imageIds.size(); i++) {
            // 初始化各图片状态均为未选中
            imageStatues.put(i, false);
        }
    }

    @Override
    public int getCount() {
        return imageIds.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = null;
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(50, 50));
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageDrawable(makeBmp(imageIds.get(position), imageStatues.get(position)));
        return imageView;
    }

    private LayerDrawable makeBmp(int id, boolean isSelect) {
        Bitmap imageBmp = ((BitmapDrawable) context.getResources().getDrawable(id)).getBitmap();
        // 根据isSelect来选取勾选的图片
        Bitmap selectedBmp = null;
        if (isSelect) {
            selectedBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.checkbox_pressed);
        } else {
            selectedBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.checkbox_normal);
        }
        // 生成叠加图
        Drawable[] drawArr = new Drawable[2];
        drawArr[0] = new BitmapDrawable(imageBmp);
        drawArr[1] = new BitmapDrawable(selectedBmp);
        LayerDrawable layerDrawable = new LayerDrawable(drawArr);
        layerDrawable.setLayerInset(0, 0, 0, 0, 0);
        layerDrawable.setLayerInset(1, 0, 0, 60, 60);

        return layerDrawable;
    }

    // 修改选中的状态
    public void changeState(int position) {
        if (isMultiSelect) { // 多选
            // 直接取反
            imageStatues.put(position, !imageStatues.get(position));
        } else { // 单选
            if (lastPosition != -1 && lastPosition != position) {
                // 取消上一次的选中状态
                imageStatues.put(lastPosition, false);
            }
            // 直接取反
            imageStatues.put(position, !imageStatues.get(position));
            lastPosition = position; // 记录本次选中的位置
        }
        notifyDataSetChanged(); // 通知适配器进行更新
    }
}
GridViewMainActivity.xml
package cn.lynn.gridview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class GridViewMainActivity extends Activity {
    // 单选网格视图
    private GridView radioGridView;
    // 多选网格视图
    private GridView checkGridView;
    // 用于单选网格视图的内容适配器
    private ImageAdapter radioImageAdapter;
    // 用于多选网格视图的内容适配器
    private ImageAdapter checkImageAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        radioGridView = (GridView) this.findViewById(R.id.radioGridView);
        radioImageAdapter = new ImageAdapter(this, false);
        radioGridView.setAdapter(radioImageAdapter);
        // 设置点击图片事件监听
        radioGridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                radioImageAdapter.changeState(position);
            }
        });

        checkGridView = (GridView) findViewById(R.id.checkGridView);
        checkImageAdapter = new ImageAdapter(this, true);
        checkGridView.setAdapter(checkImageAdapter);
        // 设置点击图片事件监听
        checkGridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                checkImageAdapter.changeState(position);
            }
        });
    }

}

三、案例效果展示

Android玉石短剑之GridView之精挑细选_第2张图片 Android玉石短剑之GridView之精挑细选_第3张图片

你可能感兴趣的:(android,GridView,multi,imageview,layerdrawable)