自定义TextView, 实现基础的更改字符串中颜色..
通常实现更改,有的人想到使用多个textview 来实现,现在来自定义view, 来动态更改字符串颜色。
首先看下自定义view,
MuiltiColorTextView.java
public class MuiltiColorTextView extends TextView {
private int mStart;
private int mEnd;
private int mTextColor;
private SpannableStringBuilder mStyle;
public MuiltiColorTextView(Context context) {
this(context, null);
}
public MuiltiColorTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MuiltiColorTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView(context,attrs);
}
public void initView(Context context,AttributeSet attrs){
TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MultiTextColor);
mStart = tArray.getInteger(R.styleable.MultiTextColor_text_start, 0);
mEnd = tArray.getInteger(R.styleable.MultiTextColor_text_end, 0);
mTextColor = tArray.getInteger(R.styleable.MultiTextColor_text_color, 0);
tArray.recycle();
}
public void updateText() {
if (this.getText().toString() != null){
//将str字符串载入SpannableStringBuilder对象中
mStyle = new SpannableStringBuilder(this.getText().toString());
}
if(mEnd<=getText().length()){
mStyle.setSpan(new ForegroundColorSpan(mTextColor), mStart, mEnd, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
setText(mStyle);
}
public void setmTextColor(int mTextColor){
this.mTextColor=mTextColor;
}
}
首先看看自定义view,继承TextView, 自然继承了 getText() ,,getTextSize() 等textView 的原始方法。
其中定义的变量 mStart 是字符串初始更改位置,mEnd是字符串结束更改位置,mTextColor是字符串更改颜色,SpannableStringBuilder是字符串拼接对象
public void initView(Context context,AttributeSet attrs){
TypedArray tArray = context.obtainStyledAttributes(attrs, R.styleable.MultiTextColor);
mStart = tArray.getInteger(R.styleable.MultiTextColor_text_start, 0);
mEnd = tArray.getInteger(R.styleable.MultiTextColor_text_end, 0);
mTextColor = tArray.getInteger(R.styleable.MultiTextColor_text_color, 0);
tArray.recycle();
}
这是自定义view ,获取自定义属性。
定义attr.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MultiTextColor">
<attr name="text_start" format="integer"></attr>
<attr name="text_end" format="integer"></attr>
<attr name="text_color" format="integer"></attr>
</declare-styleable>
</resources>
在activity中调用
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LogUtil.getInstance().i("oncreate");
setContentView(R.layout.activity_main);
MuiltiColorTextView textView=(MuiltiColorTextView)findViewById(R.id.tv_view);
textView.setmTextColor(getResources().getColor(R.color.colorAccent));
textView.updateText();
}
}
利用 自定义view,中的 setmTextColor() 设置更改颜色
updateText()做出更改字符串样式。
源码地址:
http://download.csdn.net/detail/xiabing082/9737424
参考
http://blog.csdn.net/lovexjyong/article/details/17021235