(1)布局文件就不在说明了,主要说代码的实现,先把代码贴上!
package com.example.cl; import android.annotation.SuppressLint; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Spinner; @SuppressLint({ "NewApi", "ValidFragment" }) public class Yezhuinformation extends Fragment{ private Spinner city; private Spinner quorxian; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v=inflater.inflate(R.layout.yezhuinformation, container, false); city=(Spinner)v.findViewById(R.id.city); quorxian = (Spinner)v.findViewById(R.id.quorxian); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.city, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_item); city.setAdapter(adapter); city.setOnItemSelectedListener(listener); return v; } OnItemSelectedListener listener = new OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Spinner spinner = (Spinner)parent; String pro = spinner.getSelectedItem().toString(); ArrayAdapter<CharSequence> xianorquAdapter = ArrayAdapter.createFromResource (getActivity(), R.array.zhengzhou, android.R.layout.simple_spinner_item); if(pro.equals("武汉")) { xianorquAdapter = ArrayAdapter.createFromResource (getActivity(), R.array.wuhan, android.R.layout.simple_spinner_item); } else if(pro.equals("南阳")) { xianorquAdapter = ArrayAdapter.createFromResource (getActivity(), R.array.nanyang, android.R.layout.simple_spinner_item); } if(pro.equals("郑州")) { xianorquAdapter = ArrayAdapter.createFromResource (getActivity(), R.array.zhengzhou, android.R.layout.simple_spinner_item); } else if(pro.equals("杭州")) { xianorquAdapter = ArrayAdapter.createFromResource (getActivity(), R.array.hangzhou, android.R.layout.simple_spinner_item); } quorxian.setAdapter(xianorquAdapter); } public void onNothingSelected(AdapterView<?> parent) { } }; }(2)接下来喷一下在activity中实现省市联动的代码
再喷一下在fragment中实现省市联动的主要代码
ArrayAdapter<CharSequence> xianorquAdapter = ArrayAdapter.createFromRes (getActivity(), R.array.zhengzhou, android.R.layout.simple_spinner_item);
差别在createFromRes的第一个参数上,主要是因为子类不同,切记。
联动时只要用setOnItemSelectedListener(listener);进行监听,可以通过两种方法实现联动,第一个是获取条目的位置,第二个是获取条目的内容,我采用的是第二个。
这样就可以实现省市联动了!
fragment 中利用spinner实现省市联动,布布扣,bubuko.com
原文:http://blog.csdn.net/liuzuyi200/article/details/36692219