TextView 部分字体高亮
TextView 部分字体高亮
[功能]
TextView是不支持部分字段高亮的 但是我们可以进行扩展
[思路]
1. 利用LinearLayout 作为 TextView 的 容器
2. 字符串中每个字都使用一个TextView显示之
3. 还可以使用*.9.png来作为所有TextView的背景 使之看上去成为整体
[思路 步骤]
1. 定义TextSelectionHelper 构造函数 传入 Activity上下文 及 子View对齐方式 以及 layout_width layout_height
- public class TextHighlightHelper{
- Activity activity;
- LinearLayout lLayout;
- public TextHighlightHelper(Activity a,int l){
- activity = a;
- lLayout = new LinearLayout(activity);
- lLayout.setOrientation(l);
- lLayout.setLayoutParams(
- new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
- }
- }
2. 定义函数 用于接收字符串
- //之所以每个字符都分别用一个TextView显示之 因为这样做 会使得后面颜色设定非常容易
- public void addText(CharSequence cs){
- for(int i=0;i<cs.length();i++){
- TextView tv = new TextView(activity);
- tv.setText(cs.charAt(i)+"");
- lLayout.addView(tv);
- }
- }
3. 设定 部分字符 颜色
- //函数解释: 从s开始 选取l个字符 颜色都设定为i
- public void addColor(int s,int l,int c){
- if(l > lLayout.getChildCount()){
- //error argument
- }
- else {
- for(int i=s;i<s+l;i++){
- TextView item = (TextView)lLayout.getChildAt(i);
- item.setTextColor(c);
- }
- }
- }
4. 设定所有字符的背景 最好使用*.9.png 资源 因为长度可变
- public void addBackResource(int r){
- lLayout.setBackgroundResource(r);
- }
5. 得到整个LinearLayout 并供使用
- public View loadView(){
- return lLayout;
- }
6. 如何使用TextSelectionHelper
* TextHighlightUsage 的布局 并定义最外层的id
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:id="@+id/layout"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <TextView
- android:text="HelloText1"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
* 具体使用:
- public class TextHighlightUsage extends Activity {
- TextHighlightHelper tHelper1;
- TextHighlightHelper tHelper2;
- LinearLayout ll;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- ll = (LinearLayout)findViewById(R.id.layout);
- //Text:HelloText2
- CharSequence c1 = "HelloText2";
- tHelper1 = new TextHighlightHelper(this,LinearLayout.HORIZONTAL);
- tHelper1.addText(c1);
- tHelper1.addColor(0, 3, Color.RED);
- tHelper1.addBackResource(R.drawable.dot);
- ll.addView(tHelper1.loadView());
- //Text:创新源于模仿!
- CharSequence c2 = "创新源于模仿!";
- tHelper2 = new TextHighlightHelper(this,LinearLayout.VERTICAL);
- tHelper2.addText(c2);
- tHelper2.addColor(1, 3, Color.RED);
- ll.addView(tHelper2.loadView());
- }
- }
7. emulator 运行截图:
至于其能不能满足需求 见仁见智了 大家可以参考截图