android自定义TextView(一)
16lz
2021-01-25
自定义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"?>
在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
更多相关文章
- 分支和循环(二)(零基础学习C语言)
- android:theme 常用颜色colorPrimary,colorPrimaryDark等属性使
- Android(安卓)自定义view仿微信相机单击拍照长按录视频按钮
- Android(安卓)ToggleButton(自定义可滑动的ToggleButton控件)
- Android解析自定义xml文件--Pull解析xml文件,测试demo(方案三)
- android 自定义adapter extends BaseAdapter,做有自己布局的listV
- 格式化字符串长度,超出部分显示省略号,区分汉字跟字母
- ANR超时时间的定义 .
- Android无线管理