Kotlin: Как изменить текст и цвет кнопки при нажатии? - PullRequest
0 голосов
/ 23 апреля 2020

Я хочу изменить цвет и текст кнопки при нажатии кнопки, без использования ToogleButton. И я установил файл xml следующим образом.

<Button
            android:id="@+id/downloadButton"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:text="Download"
            android:textAllCaps="false"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

И я сделал код в основной активности:

 override fun onDownloadClick(item: ProjectListDataModel, position: Int) {
       downloadButton.setOnClickListener {
            if (downloadButton.getText() == "Download") {
                downloadButton.setText("Downloaded")
                downloadButton.setBackgroundColor(ContextCompat.getColor(this,R.color.blue))
            } else if (downloadButton.getText() == "Downloaded") {
                downloadButton.setText("Download")
                downloadButton.setBackgroundColor(ContextCompat.getColor(this,R.color.gray))
            }
        }
    }

И это Adopter

class ServerProjectsRecyclerAdapter(
    val list:List<ProjectListDataModel>,
    var serverClickListener: ServerProjectListActivity) : RecyclerView.Adapter<ServerProjectRecyclerViewHolder>() {

    interface OnProjectListClickListener {
        fun onServerProjectListClick(item: ProjectListDataModel, position: Int)
        fun onDownloadClick(item: ProjectListDataModel, position: Int)
    }

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

    }

    override fun getItemCount(): Int {
        return list.count()
    }

    override fun onBindViewHolder(holder: ServerProjectRecyclerViewHolder, position: Int) {
        holder.initialize(list.get(position), serverClickListener)
    }
}

class ServerProjectRecyclerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    fun initialize(
        item: ProjectListDataModel,
        action: ServerProjectListActivity
    ) {
        itemView.projectListView.text = item.name
        itemView.modifiedTimeText.text = item.modTime
        //itemView.descriptionText.text = item.description
        itemView.setOnClickListener {
            action.onServerProjectListClick(item, adapterPosition)
        }
        itemView.downloadButton.setOnClickListener {
            action.onDownloadClick(item, adapterPosition)
        }
    }
}

вроде нет ошибок, но не работает. Есть некоторые примеры использования java, но не Kotlin.

Вот учебник java, что я хочу сделать.

https://www.youtube.com/watch?v=OVmLLet9aAQ

Доза кто-нибудь знает в чем проблема?

Ответы [ 2 ]

1 голос
/ 23 апреля 2020

Здесь измените свой интерфейс следующим образом.

interface OnProjectListClickListener {
  fun onServerProjectListClick(item: ProjectListDataModel, position: Int)
  fun onDownloadClick(button:Button,item: ProjectListDataModel, position: Int)
}

измените следующее в вашем viewholder классе

itemView.downloadButton.setOnClickListener {
            action.onDownloadClick(it,item, adapterPosition)
        }

и, наконец, в своей деятельности сделайте следующее.

 override fun onDownloadClick(button:Button,item: ProjectListDataModel, position: Int) {

    if (button.getText() == "Download") {
      button.setText("Downloaded")
      button.setBackgroundColor(ContextCompat.getColor(this,R.color.blue))
    } else if (button.getText() == "Downloaded") {
      button.setText("Download")
      button.setBackgroundColor(ContextCompat.getColor(this,R.color.gray))
    }
}
0 голосов
/ 23 апреля 2020

Это свойство, которое вы должны использовать:

android:backgroundTint="@android:color/white"

Измените свой onClickListener, как показано ниже:

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

    downloadButton?.setOnClickListener {
        if (downloadButton.getText() == "Download") {
            downloadButton.setText("Downloaded")
            downloadButton.setBackgroundTint(android.R.color.black)
        } else if (downloadButton.getText() == "Downloaded") {
            downloadButton.setText("Download")
            downloadButton.setBackgroundTint(android.R.color.holo_red_dark)
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...