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

如何访问函数局部变量?Android Spinner选中值获取方法

解决Spinner选中值的跨函数使用问题

有两种实用方法可以实现你的需求:

方法一:将选中值保存为类成员变量

把selectedCountry定义为Activity的类级变量,这样类内所有函数都能访问它。修改后的代码如下:

class MainActivity : ComponentActivity() {
    // 定义类级变量存储选中的国家
    private var selectedCountry: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(currencyconvertermain)
        val ConvertCurrency = findViewById<Button>(R.id.convertcurrency)
        val CurrencyOutput = findViewById<TextView>(R.id.currencyoutput)
        val CurrencyInput = findViewById<EditText>(R.id.currencyinput)
        val CountrySelect = findViewById<Spinner>(R.id.CountrySelect)
        val CountryImage = findViewById<ImageView>(R.id.CurrencyFlag)
        val CountrySelectAdapter = ArrayAdapter.createFromResource(this, R.array.dropdown_items, android.R.layout.simple_spinner_dropdown_item,)
        CountrySelect.adapter = CountrySelectAdapter

        CountrySelect.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parentView: AdapterView<*>,
                selectedItemView: View?,
                position: Int,
                id: Long,
            ) {
                // 更新类变量的值
                selectedCountry = parentView.getItemAtPosition(position).toString()
                when(selectedCountry) {
                    "Japan" -> CountryImage.setImageResource(R.drawable.japan)
                    "Philippines" -> CountryImage.setImageResource(R.drawable.philippines) // 修正拼写错误
                    "Nepal" -> CountryImage.setImageResource(R.drawable.nepal)
                    "Vietnam" -> CountryImage.setImageResource(R.drawable.vietnam)
                    "Taiwan" -> CountryImage.setImageResource(R.drawable.taiwan)
                }
            }

            override fun onNothingSelected(parentView: AdapterView<*>) {}
        }

        // 示例:在按钮点击事件中使用selectedCountry
        ConvertCurrency.setOnClickListener {
            selectedCountry?.let { country ->
                CurrencyOutput.text = "选中的国家:$country"
                // 这里可以添加货币转换等业务逻辑
            }
        }
    }
}

方法二:直接获取Spinner当前选中值

无需额外存储变量,每次需要时直接从Spinner实例获取当前选中项:

// 在需要获取选中值的位置调用以下代码
val currentSelectedCountry = CountrySelect.selectedItem?.toString()

// 示例:按钮点击时直接获取
ConvertCurrency.setOnClickListener {
    val country = CountrySelect.selectedItem?.toString()
    country?.let {
        CurrencyOutput.text = "当前选中:$it"
    }
}

注意事项

  • 方法二更适合仅在特定操作(如按钮点击)时获取值的场景,无需维护额外变量。
  • 方法一适合需要在多个地方频繁使用选中值,或需要实时跟踪状态变化的场景。
  • 原代码中Phillipenes存在拼写错误,建议修正为Philippines,避免匹配逻辑失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 14:47:24