【问题标题】:Android: Set TextView color on click like in the ListViewAndroid:在 ListView 中单击时设置 TextView 颜色
【发布时间】:2012-05-31 08:10:03
【问题描述】:

我的 LinearLayout 中有一些 textView。 它们是可点击的,我想让它们像 ListView 一样 onClick。 对于listView,当用户单击一个项目时,我认为背景变为绿色。

我知道我可以手动执行此操作

tv.SetBackgroundColor(Color.GREEN);

但是是否有自动执行此操作的方法,例如自动管理选择的 listView。

谢谢。

【问题讨论】:

标签: android android-listview textview


【解决方案1】:

您需要将背景定义为一个包含状态列表的新 XML 文件。

http://developer.android.com/guide/topics/resources/color-list-resource.html

例如,在您的可绘制文件夹中创建一个名为 background_states.xml 的文件并编写如下内容:

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

然后将这个新文件定义为 TextView 中的背景:

<TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:background="@drawable/background_states"

有关不同状态的更多信息,请参阅上面的链接。

【讨论】:

  • 这似乎是个好主意。我有一个问题,我在 xml 文件中收到此错误:错误:错误:找不到与给定名称匹配的资源(在 'drawable' 处,值为 '@Color/green')。
  • @color/color_name 格式用于自定义颜色,它们必须在 res/values/colors.xml 文件中定义。如果你想使用Android预定义的颜色,你应该写@android:color/green
  • 嗯,这对我不起作用,我在线性布局中动态(以编程方式)添加 TextView。我对每台电视都做了什么,我正在使用 tv.setBackgroundColor(R.drawable.background_states);但是当点击时,什么都没有改变。
  • 你可以试试 tv.setBackgroundResource(R.drawable.background_states) 吗?
  • 我现在收到这个错误 E/AndroidRuntime(2768): Caused by: org.xmlpull.v1.XmlPullParserException: Binary XML file line #5: tag requires a 'drawable' attribute or定义可绘制对象的子标签
猜你喜欢
  • 1970-01-01
  • 2013-08-06
  • 2011-03-18
  • 2013-09-27
  • 2017-01-12
  • 2012-11-06
  • 2011-04-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多