android TextView:单击更改文本颜色

时间:2010-12-17 06:53:53

标签: android android-layout

我有一个文本字段,其行为类似于本地链接,单击它会从数据库中提取图像并显示它。它不会一直ping到服务器。

以下是文本视图的xml代码

<TextView android:layout_marginLeft="2dp" android:linksClickable="true"
            android:layout_marginRight="2dp" android:layout_width="wrap_content"
            android:text="@string/Beatles" android:clickable="true" android:id="@+id/Beatles"
            android:textColor="@color/Black"
            android:textSize="12dp" android:layout_height="wrap_content" android:textColorHighlight="@color/yellow" android:textColorLink="@color/yellow"  android:autoLink="all"></TextView>

问题是我想看到文本视图的颜色应该用黄色改变,而不是相同的黑色,

就像按钮行为一样,但我没有改变背景颜色,而是想改变文字颜色

2 个答案:

答案 0 :(得分:24)

我喜欢Cristian建议的内容,但扩展TextView似乎有点矫枉过正。此外,他的解决方案无法处理MotionEvent.ACTION_CANCEL事件,因此即使点击完成后您的文字仍可能保持选中状态。

为了达到这个效果,我在一个单独的文件中实现了自己的onTouchListener:

public class CustomTouchListener implements View.OnTouchListener {     
    public boolean onTouch(View view, MotionEvent motionEvent) {
    switch(motionEvent.getAction()){            
            case MotionEvent.ACTION_DOWN:
            ((TextView)view).setTextColor(0xFFFFFFFF); //white
                break;          
            case MotionEvent.ACTION_CANCEL:             
            case MotionEvent.ACTION_UP:
            ((TextView)view).setTextColor(0xFF000000); //black
                break;
    } 
        return false;   
    } 
}

然后你可以将它指定给你想要的任何TextView:

newTextView.setOnTouchListener(new CustomTouchListener());

答案 1 :(得分:3)

您可以创建自己的TextView类来扩展Android TextView类并覆盖onTouchEvent(MotionEvent event)

然后,您可以根据传递的MotionEvent修改实例文本颜色。

例如:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
       // Change color
    } else if (event.getAction() == MotionEvent.ACTION_UP) {
       // Change it back
    }
    return super.onTouchEvent(event);
}