[功能]
TextView是不支持部分字段高亮的 但是我们可以进行扩展
[思路]
1. 利用LinearLayout 作为 TextView 的 容器
2. 字符串中每个字都使用一个TextView显示之
3. 还可以使用*.9.png来作为所有TextView的背景 使之看上去成为整体
[思路 步骤]
TextHighlightHelper.java
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));
}
}
TextHighlightUsage.java
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.txt_high_light);
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.icon);
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());
TextView tv = new TextView(this);
tv.setText(Html.fromHtml("<font color=/"#ff0000/">红色</font>其它颜色"));
ll.addView(tv);
}
}
txt_high_light.xml
<?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>
7. emulator 运行截图:
From:http://griffinshi.javaeye.com/blog/604444