Quantcast
Channel: CSDN博客移动开发推荐文章
Viewing all articles
Browse latest Browse all 5930

Android省市区三级联动的实现

$
0
0

在最近的项目中要用到一个城市的选择,由于城市选择的风格是由本公司UI设计师设计的,相当于自己定义风格的城市联动选择器,本着对UI设计师设计的尊重。我自己便写了这样一个城市选择器。
大体上来说,实现的原理没有发生改变,我是将所有的城市资源放在本地数据进行操作的,只是在风格上和常规的有点变化,希望对大家,也包括咱家猫猫,有所帮助,嘿嘿。


项目结构如下:

这里写图片描述


下面先看看效果图(界面没做优化):

这里写图片描述


  1. MainActivity代码如下:
package com.scl.city;

import java.util.ArrayList;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    private TextView sheng, shi, qu;
    private GridView gridview;
    private DBManager dbm;
    private SQLiteDatabase db;
    private String province = null;// 省
    private String city = null;// 市
    private String district = null;// 区

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /**
         * 初始化控件
         */
        sheng = (TextView) findViewById(R.id.sheng);
        shi = (TextView) findViewById(R.id.shi);
        qu = (TextView) findViewById(R.id.qu);
        gridview = (GridView) findViewById(R.id.gridview);
        sheng.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.sheng:
            sheng();
            sheng.setTextColor(Color.parseColor("#FF0000"));
            shi.setTextColor(Color.parseColor("#000000"));
            qu.setTextColor(Color.parseColor("#000000"));
            break;
        }
    }

    /**
     * 查询省
     */

    public void sheng() {
        // 创建数据库类对象
        dbm = new DBManager(this);
        // 打开本地数据库资源
        dbm.openDatabase();
        // 获取数据库省数据
        db = dbm.getDatabase();
        final ArrayList<MyListItem> list = new ArrayList<MyListItem>();

        try {
            String sql = "select * from province";
            Cursor cursor = db.rawQuery(sql, null);
            cursor.moveToFirst();
            while (!cursor.isLast()) {
                String code = cursor.getString(cursor.getColumnIndex("code"));
                byte bytes[] = cursor.getBlob(2);
                String name = new String(bytes, "gbk");
                MyListItem myListItem = new MyListItem();
                myListItem.setName(name);
                myListItem.setPcode(code);
                list.add(myListItem);
                cursor.moveToNext();
            }
            String code = cursor.getString(cursor.getColumnIndex("code"));
            byte bytes[] = cursor.getBlob(2);
            String name = new String(bytes, "gbk");
            MyListItem myListItem = new MyListItem();
            myListItem.setName(name);
            myListItem.setPcode(code);
            // 将所有的省的名称和编号放入list集合中,方便在下面显示
            list.add(myListItem);

        } catch (Exception e) {
        }
        // 查询数据完毕后,关闭数据库连接
        dbm.closeDatabase();
        db.close();

        Log.i("wujie", list.size() + "个省" + list.get(0).getName());

        Adapter adapter = new Adapter(MainActivity.this, list);
        // 设置GridView的适配器为新建的adapter
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                // 点击省份后,通过点击的位置,在ArrayList中找出该省的名称和编号
                String province_code = list.get(position).getPcode();
                province = list.get(position).getName();
                Log.i("wujie", province_code + "的" + province);
                // 通过省的编号查找该省所对应的市
                shi(province_code);
                sheng.setTextColor(Color.parseColor("#000000"));
                shi.setTextColor(Color.parseColor("#ff0000"));
            }
        });
    }

    /**
     * 查询市
     * 
     * @param pcode
     */

    public void shi(String pcode) {
        dbm = new DBManager(this);
        dbm.openDatabase();
        db = dbm.getDatabase();
        final ArrayList<MyListItem> list = new ArrayList<MyListItem>();

        try {
            String sql = "select * from city where pcode='" + pcode + "'";
            Cursor cursor = db.rawQuery(sql, null);
            cursor.moveToFirst();
            while (!cursor.isLast()) {
                String code = cursor.getString(cursor.getColumnIndex("code"));
                byte bytes[] = cursor.getBlob(2);
                String name = new String(bytes, "gbk");
                MyListItem myListItem = new MyListItem();
                myListItem.setName(name);
                myListItem.setPcode(code);
                list.add(myListItem);
                cursor.moveToNext();
            }
            String code = cursor.getString(cursor.getColumnIndex("code"));
            byte bytes[] = cursor.getBlob(2);
            String name = new String(bytes, "gbk");
            MyListItem myListItem = new MyListItem();
            myListItem.setName(name);
            myListItem.setPcode(code);
            list.add(myListItem);

        } catch (Exception e) {
        }
        dbm.closeDatabase();
        db.close();
        Log.i("wujie", list.size() + "个市区" + list.get(0).getName());
        Adapter adapter = new Adapter(MainActivity.this, list);
        // 设置GridView的适配器为新建的adapter
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                String city_code = list.get(position).getPcode();
                city = list.get(position).getName();
                qu(city_code);
                Log.i("wujie", city_code + "的" + city);
                shi.setTextColor(Color.parseColor("#000000"));
                qu.setTextColor(Color.parseColor("#ff0000"));
            }
        });
    }

    /**
     * 查询区,县
     * 
     * @param pcode
     */

    public void qu(String pcode) {
        dbm = new DBManager(this);
        dbm.openDatabase();
        db = dbm.getDatabase();
        final ArrayList<MyListItem> list = new ArrayList<MyListItem>();

        try {
            String sql = "select * from district where pcode='" + pcode + "'";
            Cursor cursor = db.rawQuery(sql, null);
            cursor.moveToFirst();
            while (!cursor.isLast()) {
                String code = cursor.getString(cursor.getColumnIndex("code"));
                byte bytes[] = cursor.getBlob(2);
                String name = new String(bytes, "gbk");
                MyListItem myListItem = new MyListItem();
                myListItem.setName(name);
                myListItem.setPcode(code);
                list.add(myListItem);
                cursor.moveToNext();
            }
            String code = cursor.getString(cursor.getColumnIndex("code"));
            byte bytes[] = cursor.getBlob(2);
            String name = new String(bytes, "gbk");
            MyListItem myListItem = new MyListItem();
            myListItem.setName(name);
            myListItem.setPcode(code);
            list.add(myListItem);

        } catch (Exception e) {
        }
        dbm.closeDatabase();
        db.close();

        Adapter adapter = new Adapter(MainActivity.this, list);
        // 设置GridView的适配器为新建的simpleAdapter
        gridview.setAdapter(adapter);

        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v,
                    int position, long id) {
                String district_code = list.get(position).getPcode();
                district = list.get(position).getName();
                Log.i("wujie", district_code + "的" + district);
                Toast.makeText(MainActivity.this, province + city + district, 1)
                        .show();
            }
        });
    }
}

2.实体类MyListItem:

package com.scl.city;

public class MyListItem {
    private String name;//省,市,区名称
    private String pcode;//对应编号
    public String getName(){
        return name;
    }
    public String getPcode(){
        return pcode;
    }
    public void setName(String name){
        this.name=name;
    }
    public void setPcode(String pcode){
        this.pcode=pcode;
    }
}

3.数据库管理类DBManager

package com.scl.city;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; 
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;
import android.util.Log;

public class DBManager {
    private final int BUFFER_SIZE = 1024;
    public static final String DB_NAME = "city_cn.s3db";
    public static final String PACKAGE_NAME = "com.scl.city";
    public static final String DB_PATH = "/data"
            + Environment.getDataDirectory().getAbsolutePath() + "/"+ PACKAGE_NAME;
    private SQLiteDatabase database;
    private Context context;
    private File file=null;

    DBManager(Context context) {
        Log.e("scl", "DBManager");
        this.context = context;
    }

    public void openDatabase() {
        Log.e("scl", "openDatabase()");
        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);
    }
    public SQLiteDatabase getDatabase(){
        Log.e("scl", "getDatabase()");
        return this.database;
    }

    private SQLiteDatabase openDatabase(String dbfile) {
        try {
            Log.e("scl", "open and return");
            file = new File(dbfile);
            if (!file.exists()) {
                Log.e("scl", "file");
                InputStream is = context.getResources().openRawResource(R.raw.city);
                if(is!=null){
                    Log.e("scl", "is null");
                }else{
                }
                FileOutputStream fos = new FileOutputStream(dbfile);
                if(is!=null){
                    Log.e("scl", "fosnull");
                }else{
                }
                byte[] buffer = new byte[BUFFER_SIZE];
                int count = 0;
                while ((count =is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                        Log.e("scl", "while");
                    fos.flush();
                }
                fos.close();
                is.close();
            }
            database = SQLiteDatabase.openOrCreateDatabase(dbfile,null);
            return database;
        } catch (FileNotFoundException e) {
            Log.e("scl", "File not found");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("scl", "IO exception");
            e.printStackTrace();
        } catch (Exception e){
            Log.e("scl", "exception "+e.toString());
        }
        return null;
    }
    public void closeDatabase() {
        Log.e("scl", "closeDatabase()");
        if(this.database!=null)
            this.database.close();
    }
}

4.城市列表适配器Adapter

package com.scl.city;

import java.util.ArrayList;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class Adapter extends BaseAdapter{

    LayoutInflater inflater = null;
    ArrayList<MyListItem> listInfo;
    public Adapter(Context context,ArrayList<MyListItem> listInfo){
        inflater = LayoutInflater.from(context);
        //this.inflater = inflater;
        this.listInfo = listInfo;
    }
    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listInfo.size();
    }
    @Override
    public Object getItem(int index) {
        // TODO Auto-generated method stub
        return listInfo.get(index);
    }
    @Override
    public long getItemId(int index) {
        // TODO Auto-generated method stub
        return index;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;
        if(convertView == null || convertView.getTag() == null){
            convertView = inflater.inflate(R.layout.item,null);
            holder = new ViewHolder();

            holder.textView = (TextView)convertView.findViewById(R.id.textview);
            convertView.setTag(holder);
        }else{

            holder = (ViewHolder)convertView.getTag();
        }
        MyListItem appInfo = listInfo.get(position);
        holder.textView.setText(appInfo.getName());
        return convertView;
    }
    public class ViewHolder{
        TextView textView;
    }


}

下面就是布局
主布局main_activity

<RelativeLayout
     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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.scl.city.MainActivity" >
<RelativeLayout 
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >
    <TextView
        android:id="@+id/sheng"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="省" 
        android:layout_alignParentLeft="true"/>

<TextView
    android:id="@+id/shi"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="市" 
        android:layout_centerHorizontal="true"/>
<TextView
    android:id="@+id/qu"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="区" 
        android:layout_alignParentRight="true"/>
</RelativeLayout>
<GridView 
    android:layout_below="@id/rl"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/gridview"
    android:numColumns="4"
    ></GridView>
</RelativeLayout>

Gridview的子布局ietm

<?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" >
   <TextView 
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:id="@+id/textview"
       android:text="123"/> 

</LinearLayout>

最后,大家别忘了还有省,市,区 的资源文件,该资源文件放在项目中的res中创建的raw包下面。
源码下载下载地址

作者:Banboofly 发表于2016/12/12 17:28:48 原文链接
阅读:47 评论:0 查看评论

Viewing all articles
Browse latest Browse all 5930

Trending Articles