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

Android开发:如何获取Spinner选中项的对应ID值

Solution: Retrieve Selected Item's ID from Spinner

Got it—you're halfway there! The key here is to link the id and name values together so you don't have to guess which ID corresponds to the selected name later. Here's a step-by-step approach to make this work:

1. Create a Data Model Class

First, define a class to hold both the id and name from your REST response. This keeps both values paired in the Spinner.

Kotlin:

data class Location(
    val id: String,
    val name: String
)

Java:

public class Location {
    private String id;
    private String name;

    public Location(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() { return id; }
    public String getName() { return name; }
}

You'll also need a top-level class to parse the full REST response:

Kotlin:

data class ApiResponse(
    val code: Int,
    val message: String,
    val data: List<Location>
)

Java:

public class ApiResponse {
    private int code;
    private String message;
    private List<Location> data;

    // Getters and setters
    public List<Location> getData() { return data; }
}

2. Parse the REST Response into a List of Models

Use your preferred JSON parser (like Gson or Moshi) to convert the response into a list of Location objects. Example with Gson:

Kotlin:

val responseJson = // Your raw REST response string
val gson = Gson()
val apiResponse = gson.fromJson(responseJson, ApiResponse::class.java)
val locationList = apiResponse.data // List<Location> ready for the Spinner

Java:

String responseJson = // Your raw REST response string
Gson gson = new Gson();
ApiResponse apiResponse = gson.fromJson(responseJson, ApiResponse.class);
List<Location> locationList = apiResponse.getData();

3. Create a Custom Spinner Adapter

Instead of a basic ArrayAdapter (which only holds strings), use a custom adapter that displays the name but retains the full Location object.

Kotlin:

class LocationAdapter(
    context: Context,
    private val locations: List<Location>
) : ArrayAdapter<Location>(context, android.R.layout.simple_spinner_item, locations) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = super.getView(position, convertView, parent)
        (view as TextView).text = locations[position].name
        return view
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        val view = super.getDropDownView(position, convertView, parent)
        (view as TextView).text = locations[position].name
        return view
    }
}

Java:

public class LocationAdapter extends ArrayAdapter<Location> {
    private List<Location> locations;

    public LocationAdapter(Context context, List<Location> locations) {
        super(context, android.R.layout.simple_spinner_item, locations);
        this.locations = locations;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = super.getView(position, convertView, parent);
        TextView textView = (TextView) view;
        textView.setText(locations.get(position).getName());
        return view;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        View view = super.getDropDownView(position, convertView, parent);
        TextView textView = (TextView) view;
        textView.setText(locations.get(position).getName());
        return view;
    }
}

4. Attach the Adapter and Handle Selection

Finally, set up the Spinner with your custom adapter, then listen for selections to get the associated id:

Kotlin:

val spinner = findViewById<Spinner>(R.id.your_spinner_id)
val adapter = LocationAdapter(this, locationList)
spinner.adapter = adapter

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
    override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        val selectedLocation = adapter.getItem(position)
        val selectedId = selectedLocation.id
        // Use this ID for your next REST request (e.g., fetch cities by province ID)
        fetchCitiesByProvinceId(selectedId)
    }

    override fun onNothingSelected(parent: AdapterView<*>?) {
        // Handle case where no item is selected (optional)
    }
}

Java:

Spinner spinner = findViewById(R.id.your_spinner_id);
LocationAdapter adapter = new LocationAdapter(this, locationList);
spinner.setAdapter(adapter);

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        Location selectedLocation = adapter.getItem(position);
        String selectedId = selectedLocation.getId();
        // Use this ID for your next REST request
        fetchCitiesByProvinceId(selectedId);
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Handle no selection (optional)
    }
});

Quick Tip

This approach ensures you never have to worry about matching names to IDs manually (even if names are duplicated). The Location model keeps everything linked neatly.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:42:52