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

Room数据库问题:Spinner显示POJO结构而非目标货币数据如何解决?

解决Spinner显示Room实体类POJO结构而非货币代码的问题

方法1:重写实体类的toString()方法

修改CurrencyDatabaseModel,重写toString()方法直接返回货币代码:

@Entity(tableName = "currencies")
data class CurrencyDatabaseModel(
    @PrimaryKey @ColumnInfo(name = "currency_name") val currency: String
) {
    override fun toString(): String = currency
}

Spinner默认会调用列表项的toString()方法,重写后即可直接显示USD、EUR这类代码,无需改动其他Adapter逻辑。

方法2:在数据层直接返回货币代码列表

步骤1:修改DAO查询语句

直接查询货币名字段,返回字符串列表的Flow:

@Dao
interface CurrencyDAO {
    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertNewCurrency(databaseModel: CurrencyDatabaseModel)

    @Query("SELECT currency_name FROM currencies ORDER BY currency_name")
    fun getAllCurrencyCodes(): Flow<List<String>>
}

步骤2:更新仓库层

class CurrencyDatabaseRepository(private val currencyDAO: CurrencyDAO) {
    val allCurrencyCodes: Flow<List<String>> = currencyDAO.getAllCurrencyCodes()

    @Suppress("RedundantSuspendModifier")
    @WorkerThread
    suspend fun insertNewCurrency(currencyDatabaseModel: CurrencyDatabaseModel){
        currencyDAO.insertNewCurrency(currencyDatabaseModel)
    }
}

步骤3:更新ViewModel

class CurrencyDatabaseViewModel(private val currencyDatabaseRepository: CurrencyDatabaseRepository) :
ViewModel() {
    val allCurrencyCodes: LiveData<List<String>> = currencyDatabaseRepository.allCurrencyCodes.asLiveData()
}

后续Spinner的Adapter直接使用这个字符串列表即可。

方法3:自定义Spinner的ArrayAdapter

如果不想修改实体类或数据层,可以自定义Adapter,在绑定视图时提取货币代码:

// 在Activity/Fragment中设置Spinner Adapter
val adapter = object : ArrayAdapter<CurrencyDatabaseModel>(
    this,
    android.R.layout.simple_spinner_item,
    // 此处传入ViewModel中的allCurrencies数据列表
    viewModel.allCurrencies.value ?: emptyList()
) {
    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        val textView = super.getView(position, convertView, parent) as TextView
        textView.text = getItem(position)?.currency ?: ""
        return textView
    }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
        val textView = super.getDropDownView(position, convertView, parent) as TextView
        textView.text = getItem(position)?.currency ?: ""
        return textView
    }
}
binding.spinner.adapter = adapter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 09:45:50