2010-12-17 131 views
21

我有一个文本框,其行为类似于本地链接,点击它从数据库获取图像并显示它。它不会一直ping到服务器。android TextView:单击更改文本颜色

下面是文本视图中的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> 

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

刚像按钮的行为,但不是改变背景颜色我想改变文字颜色

+0

https://开头计算器.com/questions/5371719/change-clickable-textviews-color-on-focus-and-click – CoolMind 2017-10-09 16:42:59

回答

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); 
} 
23

我喜欢克里斯蒂安建议,但延长的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

感谢您的代码为我工作。我已经在你的回答中做到了回报,并为我工作。 – 2013-01-25 11:22:48