gpt4 book ai didi

android - 通过单击Kotlin中的recyclerView来更改activity_main的元素

转载 作者:行者123 更新时间:2023-12-02 13:07:46 25 4
gpt4 key购买 nike

我需要通过单击RecyclerView中的元素来更改来自activity_main.xml的Button元素的颜色。十六进制颜色值应从选定的项目参数中获取。
仅仅因为我是Kotlin的新手,所以不了解如何执行它。

enter image description here

这是MainActivity:

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

doAsync {
val json = URL("https://api.jsonbin.io/b/5e299cea5eae2c3a26db9cdf/2").readText()
d("daniel", "json? $json")
// val dataList: ArrayList<String> = ArrayList()
uiThread {
val stations = Gson().fromJson(json, Array<Stations>::class.java).toList()
ElementsList.apply{
layoutManager = LinearLayoutManager(this@MainActivity)
adapter = ElementsAdapter(stations)
}
}
}
}
}

这是ElementsAdapter(recyclerView):
class ElementsAdapter(private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_sample, parent, false)

return ViewHolder(view)
}

override fun getItemCount() = stations.size

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val stationItem = stations[position]
val highlightColor = stationItem.properties.color
val colorFilter = Color.parseColor(highlightColor)
holder.nameStation.text = stationItem.properties.color
holder.lineColor.setColorFilter(colorFilter, PorterDuff.Mode.SRC_ATOP)
holder.view.setOnClickListener{
val curValue = holder.adapterPosition
val selectedValue = stations[curValue].name

// something should be done here to change button's color

}
}

class ViewHolder(val view: View): RecyclerView.ViewHolder(view){
val nameStation: TextView = itemView.name_station
val lineColor: ImageView = itemView.line_color
}

}

最佳答案

请按照以下步骤实现此目的

步骤-1:更改ElementsAdapter的构造函数,以接收Activity实例,如下所示:

class ElementsAdapter(private val context: Context, private val stations: List<Stations>) : RecyclerView.Adapter<ElementsAdapter.ViewHolder>() {

....

}

步骤-2:MainActivity中创建一个回调函数以更改按钮的颜色
class MainActivity : AppCompatActivity() {

....

fun updateButtonColor(hexColor: String) {

// update button's color here
}
}

并在创建适配器期间传递 Activity 实例
adapter = ElementsAdapter(this@MainActivity, stations)

步骤-3:onBindViewHolderOnClickListener中,使用适当的 调用 Activity 的updateButtonColor十六进制HEX_COLOR
holder.view.setOnClickListener{
val curValue = holder.adapterPosition
val selectedValue = stations[curValue].name

//something should be done here to change button's color

(context as MainActivity).updateButtonColor(HEX_COLOR)
}

关于android - 通过单击Kotlin中的recyclerView来更改activity_main的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59910900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com