基于Spinner实现的三级联动、多级联动

废话不多说直接上代码:

import android.content.Context;
import android.content.SharedPreferences;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by chenxiaoli on 2017/3/6 0006.
 *基于Spinner实现的多级列表
 * 可以开启本地缓存,
 * 也可以通过getPosition获取索引自己实现缓存
 */

public class MultistageSpinnerHelper {
    private static final String SELETE_POSITION = "selectPosition";
    private static final String ID = "id";
    private OnAddressChangerListener listener;
    private MultistageBean[] multistageBeans;
    private ArrayList multistageBeens;
    private boolean isSaveCache;//是否使用实时缓存
    private SharedPreferences sp;
    private String id;
    private ArrayList[] arrayLists;//所有列表集合
    private int[] positions;//所有索引数组

  

    public interface OnAddressChangerListener {
        void onAddressChanger(MultistageBean[] multistageBeans);
    }

    public MultistageSpinnerHelper(ArrayList multistageBeens) {
        this.multistageBeens = multistageBeens;
    }

    /**
     * 选择条目变更的监听
     *
     * @param listener
     */
    public void setOnAddressChangeListener(OnAddressChangerListener listener) {
        this.listener = listener;

    }

    public void setSpinnerData(final Context context, final Spinner... spinners) {
        int spinnersLength = spinners.length;
        positions = new int[spinnersLength];
        initCache(context, spinnersLength);//读取缓存
        arrayLists = new ArrayList[spinnersLength];
        multistageBeans = new MultistageBean[spinnersLength];
        final List spinnerList = Arrays.asList(spinners);
        for (int i = 0; i < spinnersLength; i++) {
            arrayLists[i] = new ArrayList();
            if (i == 0) {//第一个条目是集合
                for (MultistageBean bean : multistageBeens) {
                    arrayLists[0].add(bean.name);
                }
                ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, arrayLists[i]);
                spinners[i].setAdapter(adapter);
                spinners[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {//设置首条目监听
                    @Override
                    public void onItemSelected(AdapterView parent, View view, final int position, long id) {
                        int i = spinnerList.indexOf(parent);
                        multistageBeans[i] = multistageBeens.get(position);
                        //       provincePosition = position;
                        if (isSaveCache) {//保存本地缓存
                            if (sp == null) {
                                sp = context.getSharedPreferences("MultistageSpinnerHelper" + MultistageSpinnerHelper.this.id, Context.MODE_PRIVATE);
                            }
                            sp.edit().putInt(SELETE_POSITION + i, position).commit();
                        }
                        if (listener != null) {
                            listener.onAddressChanger(multistageBeans);
                        }
                        if (i + 1 < spinners.length && multistageBeans[i].children != null) {
                            arrayLists[i + 1].clear();
                            for (MultistageBean bean : multistageBeans[i].children) {
                                arrayLists[i + 1].add(bean.name);
                            }
                            ArrayAdapter adapter22 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, arrayLists[i + 1]);
                            spinners[i + 1].setAdapter(adapter22);
                            spinners[i + 1].setSelection(positions[i + 1]);
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView parent) {

                    }
                });
            } else {
                ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_spinner_dropdown_item, arrayLists[i]);
                spinners[i].setAdapter(adapter);
                spinners[i].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {//设置其余条目监听
                    @Override
                    public void onItemSelected(AdapterView parent, View view, final int position, long id) {
                        int i = spinnerList.indexOf(parent);
                        multistageBeans[i] = multistageBeans[i - 1].children.get(position);
                        //       provincePosition = position;
                        if (isSaveCache) {//保存本地缓存
                            if (sp == null) {
                                sp = context.getSharedPreferences("MultistageSpinnerHelper" + MultistageSpinnerHelper.this.id, Context.MODE_PRIVATE);
                            }
                            sp.edit().putInt(SELETE_POSITION + i, position).commit();
                        }
                        if (listener != null) {
                            listener.onAddressChanger(multistageBeans);
                        }
                        if (i + 1 < spinners.length && multistageBeans[i] != null && multistageBeans[i].children != null) {
                            arrayLists[i + 1].clear();
                            for (MultistageBean bean : multistageBeans[i].children) {
                                arrayLists[i + 1].add(bean.name);
                            }
                            ArrayAdapter adapter22 = new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, arrayLists[i + 1]);
                            spinners[i + 1].setAdapter(adapter22);
                            spinners[i + 1].setSelection(positions[i + 1]);
                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView parent) {
                    }
                });
            }
        }
        spinners[0].setSelection(positions[0]);
    }

    /**
     * 读取本地缓存
     */
    private void initCache(Context context, int length) {
        sp = context.getSharedPreferences("MultistageSpinnerHelper" + id, Context.MODE_PRIVATE);
        for (int i = 0; i < length; i++) {
            positions[i] = sp.getInt(SELETE_POSITION + i, 0);
        }
    }

    /**
     * @return 返回选中的数据
     */
    public MultistageBean[] getMultistageBeans() {
        return multistageBeans;
    }

    /**
     * @return 返回选中的索引
     */
    public int[] getPositions() {
        return positions;
    }

    /**
     * @param saveCache
     * @param Tag,根据id存取缓存数据 是否开启多用户本地缓存
     *                       默认不开启
     *                       需要在setSpinnerAddress方法前调用
     */
    public void openCache(boolean saveCache, String Tag) {
        this.isSaveCache = saveCache;
        this.id = Tag;
    }

    /**
     * @param saveCache 是否开启单用户本地缓存
     *                  默认不开启
     *                  需要在setSpinnerAddress方法前调用
     */
    public void openCache(boolean saveCache) {
        openCache(saveCache, "");
    }
同时还需要一个这样的bean类

import java.util.List;

/**
 * Created by lee3219237 on 2017/3/2 0002.
 */

public class MultistageBean {

    /**
     * children : [{"children":[{"city_id":110100,"entityId":110101,"id":110101,"name":"东城区","persistent":true},{"city_id":110100,"entityId":110102,"id":110102,"name":"西城区","persistent":true},{"city_id":110100,"entityId":110103,"id":110103,"name":"崇文区","persistent":true},{"city_id":110100,"entityId":110104,"id":110104,"name":"宣武区","persistent":true},{"city_id":110100,"entityId":110105,"id":110105,"name":"朝阳区","persistent":true},{"city_id":110100,"entityId":110106,"id":110106,"name":"丰台区","persistent":true},{"city_id":110100,"entityId":110107,"id":110107,"name":"石景山区","persistent":true},{"city_id":110100,"entityId":110108,"id":110108,"name":"海淀区","persistent":true},{"city_id":110100,"entityId":110109,"id":110109,"name":"门头沟区","persistent":true},{"city_id":110100,"entityId":110111,"id":110111,"name":"房山区","persistent":true},{"city_id":110100,"entityId":110112,"id":110112,"name":"通州区","persistent":true},{"city_id":110100,"entityId":110113,"id":110113,"name":"顺义区","persistent":true},{"city_id":110100,"entityId":110114,"id":110114,"name":"昌平区","persistent":true},{"city_id":110100,"entityId":110115,"id":110115,"name":"大兴区","persistent":true},{"city_id":110100,"entityId":110116,"id":110116,"name":"怀柔区","persistent":true},{"city_id":110100,"entityId":110117,"id":110117,"name":"平谷区","persistent":true}],"id":110100,"name":"市辖区","parent_id":110000},{"children":[{"city_id":110200,"entityId":110228,"id":110228,"name":"密云县","persistent":true},{"city_id":110200,"entityId":110229,"id":110229,"name":"延庆县","persistent":true}],"id":110200,"name":"县","parent_id":110000}]
     * id : 110000
     * name : 北京市
     * parent_id : 0
     */

    public int id;
    public String name;
    public int parent_id;
    public List children;

}
在activity中使用它实现一个三级联动地址

import com.google.gson.reflect.TypeToken;
import com.google.gson.Gson;

public class MyActivity extends Activity{

private Spinner spinnerProvice1;//省
private Spinner spinnerCity1;//市
private Spinner spinnerCounty1;//县

private Spinner spinnerProvice2;//上班地点省
private Spinner spinnerCity2;//上班地点市
private Spinner spinnerCounty2;//上班地点县
private Button button;//下一步,保存
private MultistageSpinnerHelper multistageSpinnerHelper1;
private MultistageSpinnerHelper multistageSpinnerHelper2;
private ArrayList address;//包含省市县地址的对象

  
  @Override
    protected void onCreate(Bundle savedInstanceState) {
         setContentView(resource);
         spinnerProvice1 = findviewbyid(...);
          spinnerCity1 = findviewbyid(...);
           spinnerCounty1 = findviewbyid(...);
          spinnerProvice2 = findviewbyid(...);
          spinnerCity2 = findviewbyid(...);
           spinnerCounty2 = findviewbyid(...);
           button = findviewbyid(...);
           new Thread(){
            public void run(){
                AssetManager manager = getAssets();
                try {
                    InputStreamReader inputReader = new InputStreamReader(manager.open("city.json") );//读取asset文件夹中的地址json文件
                    BufferedReader bufReader = new BufferedReader(inputReader);
                    String line="";
                    String Result="";
                    while((line = bufReader.readLine()) != null)
                        Result += line;
                    Type type = new TypeToken>()
                    {}.getType();
                    Gson gson = new Gson();
                   address = gson.fromJson(Result, type);//将json转化为对象
                } catch (IOException e) {
                    e.printStackTrace();
                }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            multistageSpinnerHelper1 = new MultistageSpinnerHelper(address);
                            multistageSpinnerHelper1.openCache(true,"tag1"+"用户uid");//开启本地缓存,这里可以设置缓存标识,用于区别不同页面或不同用户
                            multistageSpinnerHelper1.setSpinnerData(MyActivity.this, spinnerProvice1, spinnerCity1, spinnerCounty1);
                            multistageSpinnerHelper2 = new MultistageSpinnerHelper(address);
                            multistageSpinnerHelper2.openCache(true,"tag2"+"用户uid");//开启本地缓存,这里可以设置缓存标识,用于区别不同页面或不同用户
                            multistageSpinnerHelper2.setSpinnerData(MyActivity.this, spinnerProvice2, spinnerCity2, spinnerCounty2);
                        }
                    });
            }
        }.start();
        
         button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 MultistageBean[] multistageBeen1 = multistageSpinnerHelper1.getMultistageBeans();//通过get方法
                 Toast.makeText(this,multistageBeen1[0].name+":"+ multistageBeen1[1].name+":"+ multistageBeen1[2].name,Toast.LENGTH_SHORT).show();
                  MultistageBean[] multistageBeen2 = multistageSpinnerHelper2.getMultistageBeans();//通过get方法
                 Toast.makeText(this,multistageBeen2[0].name+":"+ multistageBeen2[1].name+":"+ multistageBeen2[2].name,Toast.LENGTH_SHORT).show();
            }
        });
    }
    
}

当然目前能够实现的页面效果还非常简单,以后有时间再更新。

你可能感兴趣的:(Android)