gpt4 book ai didi

android - 将android应用程序中布局的背景颜色与kotlin进行比较

转载 作者:行者123 更新时间:2023-12-02 13:33:40 26 4
gpt4 key购买 nike

我想做一个 if 语句,在其中我将比较我的布局背景颜色的颜色,与 kotlin 类似:

    val viewPaint = (background.getBackground() as PaintDrawable).paint
val colorARGB = viewPaint.color

if(colorARGB == Color.GREEN){

btn_touch.setOnClickListener {


counter += 1
textCounter.text = counter.toString()


}
}

它不起作用我如何将背景颜色与 kotlin 进行比较?

最佳答案

我回答了your other question ,所以我有更多的上下文 :-) 您应该存储自己的应用程序状态,而不是直接比较背景颜色,这样您就可以控制它在做什么,并让背景做出相应的 react 。

enum class State {
ON,
OFF
}

从您的 GitHub 存储库中,更改循环以更新状态:
  when (Random.nextBoolean()) {
true -> state = State.ON
false -> state = State.OFF
}

然后使用该状态更新您的 UI:
private fun updateUI() {
when (state) {
State.ON -> {
background.setBackgroundColor(Color.GREEN)
}
State.OFF -> {
background.setBackgroundColor(Color.RED)
}
}
}

因此,您可以再次使用状态来响应按钮单击:
btn_touch.setOnClickListener {
when (state) {
State.ON -> reactOnClickWhenOn()
State.OFF -> reactOnClickWhenOff()
}
}

private fun reactOnClickWhenOn() {
counter += 1
}

private fun reactOnClickWhenOff() {
Toast.makeText(this, "Nope!", Toast.LENGTH_SHORT).show()
}

完整的例子:
import android.graphics.Color
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.foo.*
import kotlinx.coroutines.*
import java.util.concurrent.TimeUnit
import kotlin.random.Random

class FooActivity : AppCompatActivity() {

private var state = State.OFF
private var counter: Int = 0
private var running = false

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.foo)
val loop = true
GlobalScope.launch(Dispatchers.IO) {
while (loop) {
while (running) {
delay(TimeUnit.SECONDS.toMillis(Random.nextLong(5)))
when (Random.nextBoolean()) {
true -> state = State.ON
false -> state = State.OFF
}
withContext(Dispatchers.Main) {
updateUI()
}
}
}
}

btn_touch.setOnClickListener {
when (state) {
State.ON -> reactOnClickWhenOn()
State.OFF -> reactOnClickWhenOff()
}
}

}

private fun updateUI() {
when (state) {
State.ON -> {
background.setBackgroundColor(Color.GREEN)
}
State.OFF -> {
background.setBackgroundColor(Color.RED)
}
}
}

private fun reactOnClickWhenOn() {
counter += 1
}

private fun reactOnClickWhenOff() {
Toast.makeText(this, "Nope!", Toast.LENGTH_SHORT).show()
}

override fun onResume() {
super.onResume()
running = true
}

override fun onPause() {
running = false
super.onPause()
}

enum class State {
ON,
OFF
}
}

关于android - 将android应用程序中布局的背景颜色与kotlin进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60098765/

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