You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发:如何拆分字符串实现省市联动Spinner功能?

实现Android省市Spinner联动的解决方案

Hey there! I see you're trying to split a string to separate provinces and cities, then link two Spinners so that selecting a province loads its corresponding cities. Let's fix your code and get this working properly.

First, let's spot the issues in your current code:

  • You're using an undefined variable output3 when adding to arrayList1 – that's a typo that'll cause a compile error.
  • You're initializing and setting the ArrayAdapter inside the loop, which is inefficient and will lead to incorrect behavior.
  • You don't have a way to map provinces to their respective cities right now; you're just adding all split strings to a single list, which can't support the linkage.
  • The onItemSelected method has checks for "Income" and "Expense" which don't relate to your province-city requirement.

Here's the corrected approach:

We'll use a HashMap<String, List<String>> to store each province and its associated cities. Then we'll populate the first Spinner with province names, and when a province is selected, we'll fetch its cities from the map and update the second Spinner.

Full corrected code:

// Declare necessary variables at the class level
private ArrayList<String> provinceList;
private HashMap<String, List<String>> cityMap;
private Spinner s1, s2; // Make sure you have your second Spinner declared
private ArrayAdapter<String> provinceAdapter, cityAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout); // Replace with your layout file

    s1 = findViewById(R.id.spinner_province); // Replace with your first Spinner ID
    s2 = findViewById(R.id.spinner_city); // Replace with your second Spinner ID

    provinceList = new ArrayList<>();
    cityMap = new HashMap<>();

    String input = "Tamilnadu-Chennai,Madurai,Trichy~Kerala-Kochi,Trivandrum~Karnataka-Bengaluru,Mangalore";
    String[] provinceSections = input.split("~");

    // Parse the input string and build our province-city map
    for (String section : provinceSections) {
        String[] provinceAndCities = section.split("-");
        if (provinceAndCities.length == 2) {
            String province = provinceAndCities[0];
            String[] cityArray = provinceAndCities[1].split(",");
            List<String> cityList = new ArrayList<>(Arrays.asList(cityArray));

            provinceList.add(province);
            cityMap.put(province, cityList);
        }
    }

    // Set up the first Spinner (Provinces)
    provinceAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, provinceList);
    s1.setAdapter(provinceAdapter);

    // Set up the Spinner selection listener
    s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            String selectedProvince = provinceList.get(position);
            Toast.makeText(MainActivity.this, selectedProvince, Toast.LENGTH_SHORT).show();

            // Get the corresponding cities and update the second Spinner
            List<String> cities = cityMap.get(selectedProvince);
            if (cities != null) {
                cityAdapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, cities);
                s2.setAdapter(cityAdapter);
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            // Optional: Handle case when nothing is selected
            s2.setAdapter(null);
        }
    });
}

Key improvements explained:

  • Data Structure: The HashMap lets us quickly look up which cities belong to a selected province.
  • Efficient Parsing: We parse the input string once outside the listener, so we don't re-process it every time a selection is made.
  • Proper Adapter Setup: Adapters are created once (or only when needed for cities) instead of in a loop, which is more efficient.
  • Clear Linkage: The onItemSelected method now correctly fetches the cities for the selected province and updates the second Spinner.

内容的提问来源于stack exchange,提问作者Vinopraji

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 13:43:11