Измените элементы activity_main, щелкнув из recyclerView в Kotlin - PullRequest
1 голос
/ 25 января 2020

Мне нужно изменить цвет элемента Button с Activity_main. xml, щелкнув элемент в RecyclerView. Шестнадцатеричное значение цвета должно быть взято из параметров выбранного элемента. Просто потому, что я новичок в 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
    }

}

Ответы [ 2 ]

3 голосов
/ 25 января 2020

Выполните следующие шаги для достижения этого

Шаг - 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
    }
}

и передача экземпляра действия во время создания адаптера

adapter = ElementsAdapter(this@MainActivity, stations)

Шаг - 3: Внутри onBindViewHolder OnClickListener вызовите 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)
}
1 голос
/ 25 января 2020

Вы можете изменить фон кнопки, используя метод .setBackgroundColor(). В вашем случае вам нужно что-то вроде этого:

yourSelectedButton.setBackgroundColor(Color.parseColor(selectedValue));
...