android 改变TextView和EditText文字选中效果

来源:互联网 发布:淘宝怎么免费开店铺 编辑:程序博客网 时间:2024/05/21 17:41

欢迎转帖,但请注明地址:http://blog.csdn.net/ethan_xue/   谢谢

最近因为项目需要,更改EditText被选中时的图片,网络搜索未果,于是查看源代码

EditText代码里没什么东西,于是猜测在其父类TextView中,很快发现这样一段代码

[java] view plaincopy
  1. int mTextSelectHandleLeftRes;  
  2.   int mTextSelectHandleRightRes;  
  3.   int mTextSelectHandleRes;  
  4.   
  5.   Drawable mSelectHandleLeft;  
  6.   Drawable mSelectHandleRight;  
  7.   Drawable mSelectHandleCenter;  
看名字就猜到是这个了,google写的代码就是漂亮,根据mTextSelectHandleLeftRes找到这段代码

[java] view plaincopy
  1. case com.android.internal.R.styleable.TextView_textSelectHandleLeft:  
  2.      mTextSelectHandleLeftRes = a.getResourceId(attr, 0);  
  3.      break;  

看到R.styleable.TextView_textSelectHandleLeft,果断去查看res文件,呵呵,果然就是他

styles.xml里

[html] view plaincopy
  1. <style name="Widget.TextView">  
  2.         <item name="android:textAppearance">?android:attr/textAppearanceSmall</item>  
  3.         <item name="android:textSelectHandleLeft">?android:attr/textSelectHandleLeft</item>  
  4.         <item name="android:textSelectHandleRight">?android:attr/textSelectHandleRight</item>  
  5.         <item name="android:textSelectHandle">?android:attr/textSelectHandle</item>  
  6.     </style>  

看到?android:attr/textSelectHandleLeft去查看attr.xml,结果有以下代码

[html] view plaincopy
  1. <!-- Reference to a drawable that will be used to display a text selection  
  2.              anchor on the left side of a selection region. -->  
  3.         <attr name="textSelectHandleLeft" />  
到此只能说明有这个属性,那杯具了,只有个style,图片文件在哪里啊?于是使用强大的notepad++的查找功能,ctrl+f--文件查找--textSelectHandleLeft结果发现public.xml里和themes.xml里都有,themes.xml里是这样写的

[html] view plaincopy
  1. <!-- Text selection handle attributes -->  
  2.         <item name="textSelectHandleLeft">@android:drawable/text_select_handle_left</item>  
  3.         <item name="textSelectHandleRight">@android:drawable/text_select_handle_right</item>  
  4.         <item name="textSelectHandle">@android:drawable/text_select_handle_middle</item>  
  5.         <item name="textSelectHandleWindowStyle">@android:style/Widget.TextSelectHandle</item>  

到此终于找到图片了,替换掉后的效果


然后看到选中的字的背景是黄色的,怎样改变呢?

源码里

[java] view plaincopy
  1. /** 
  2.     * Sets the color used to display the selection highlight. 
  3.     * 
  4.     * @attr ref android.R.styleable#TextView_textColorHighlight 
  5.     */  
  6.    @android.view.RemotableViewMethod  
  7.    public void setHighlightColor(int color) {  
  8.        if (mHighlightColor != color) {  
  9.            mHighlightColor = color;  
  10.            invalidate();  
  11.        }  
  12.    }  
于是我们只要设置这个方法就可以了

效果如图

原创粉丝点击