首页 > 代码库 > fragment 中利用spinner实现省市联动
fragment 中利用spinner实现省市联动
(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中实现省市联动的代码
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.city, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
再喷一下在fragment中实现省市联动的主要代码
ArrayAdapter<CharSequence> xianorquAdapter = ArrayAdapter.createFromRes (getActivity(), R.array.zhengzhou, android.R.layout.simple_spinner_item);
差别在createFromRes的第一个参数上,主要是因为子类不同,切记。
联动时只要用setOnItemSelectedListener(listener);进行监听,可以通过两种方法实现联动,第一个是获取条目的位置,第二个是获取条目的内容,我采用的是第二个。
这样就可以实现省市联动了!
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。