android TextView:单击更改文本颜色

Pra*_*ham 21 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>
Run Code Online (Sandbox Code Playgroud)

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

就像按钮行为,但我想改变文本颜色,而不是改变背景颜色

plo*_*man 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;   
    } 
}
Run Code Online (Sandbox Code Playgroud)

然后你可以将它分配给你想要的任何TextView:

newTextView.setOnTouchListener(new CustomTouchListener());

  • 谢谢您的代码对我有用。我已经在您的回答中返回了true,并为我工作。 (2认同)

Cri*_*ian 3

您可以创建自己的 TextView 类来扩展 AndroidTextView类并覆盖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);
}
Run Code Online (Sandbox Code Playgroud)