(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(2)接下来喷一下在activity中实现省市联动的代码 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);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 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) { } };}
再喷一下在fragment中实现省市联动的主要代码
ArrayAdapter<CharSequence> xianorquAdapter = ArrayAdapter.createFromRes (getActivity(), R.array.zhengzhou, android.R.layout.simple_spinner_item);
区别在createFromRes的第一个參数上,主要是由于子类不同,切记。
联动时仅仅要用setOnItemSelectedListener(listener);进行监听,能够通过两种方法实现联动,第一个是获取条目的位置,第二个是获取条目的内容,我採用的是第二个。
这样就能够实现省市联动了!