如何从选择器更改textView颜色

时间:2012-01-03 12:06:45

标签: android background textview selector android-linearlayout

我有使用textView的LinearLayout。

我已从选择器

设置了LinearLayout背景
android:background="@drawable/tab_bg_selector"

因此在按下布局时会改变背景颜色

我的问题是如何在按布局时更改文字颜色

我需要像onStateChangeListner这样的东西,所以当用户按下布局时它也会改变文字颜色

感谢,

托默

5 个答案:

答案 0 :(得分:4)

How to make shape's child TextView white when state_pressed="true"的重复,这几乎是正确的答案。 duplicateParentState =“true”将父ListView选择状态传递给TextView子级。以下对我有用:

<TextView
    android:duplicateParentState="true"
    android:textColor="@drawable/text_selector"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

和text_selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true"
        android:color="@color/text_on" /> <!-- pressed -->
    <item android:state_focused="true"
        android:color="@color/text_on" /> <!-- focused -->
    <item android:color="@color/text_off" /> <!-- default -->
</selector>

答案 1 :(得分:3)

将其放在onClick of Layout

textview.setTextColor(颜色);

答案 2 :(得分:1)

试试这段代码 -

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
public void clickme(View view)
{
    TextView tv = (TextView)findViewById(R.id.textView1);
    tv.setTextColor(Color.RED);             
}

main.xml中

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:onClick="clickme"
android:orientation="vertical" >


<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:text="Large Text"
    android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

使用您的选择器尝试此操作。

答案 3 :(得分:1)

您可以通过两种方式将颜色设置为textview  使用xml标签“android:textcolor =”colorvalue“ 要么  通过java代码中的“textview object.setTextColor(colorname)”方法设置颜色。

答案 4 :(得分:0)

因为有一个解决方案 首先使用文本颜色在不同颜色的背景下创建两个图像 第二个是将选择器设置为您在上面应用

android:background="@drawable/tab_bg_selector"

它绝对有效