gpt4 book ai didi

android - 如何在按下时更改 TextView 背景颜色?

转载 作者:行者123 更新时间:2023-11-30 04:58:14 24 4
gpt4 key购买 nike

我尝试在按下时更改 TextView1 的背景。这是我在可绘制文件夹中的 text.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@android:color/white" />
<item android:drawable="@android:color/black"/>
</selector>

这是我的 Kotlin 文件:

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

var textview1 = findViewById(R.id.TextView1) as TextView

textview1.setOnClickListener{
val t = TextView(this)
t.setBackgroundResource(R.drawable.text)
}
}

我根据这个回答的答案做了这个:Programatically make TextView background color change while pressed

TextView1:

<TextView
android:id="@+id/TextView1"
android:layout_width="50dp"
android:layout_height="50dp"/>

有人知道我错过了什么吗?我是初学者。


对不起,这是我的代码错误。正确的代码是:

 var textview1 = findViewById(R.id.TextView1) as TextView

textview1.setOnClickListener {
//val t = TextView(this)
textview1.setBackgroundResource(R.drawable.text)

最佳答案

您需要在 onClick 事件之前而不是之后在 textview 上设置背景。现在,在处理完点击事件后,颜色会应用到新的 Textview (t) 上。该 Textview 不是在屏幕上呈现的 View (textview1)

使用以下之一:

<TextView
android:id="@+id/TextView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="@drawable/text"/>

textview1.setBackgroundResource(R.drawable.text)
textview1.setOnClickListener{
//Handle click
}

此外,如果您将代码更改为:

textview1.setOnClickListener{
textview1.setBackgroundResource(R.drawable.text)
}

您会注意到状态列表确实在第一次点击之后得到应用

关于android - 如何在按下时更改 TextView 背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58761255/

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