安卓课程十三 TextView显示表情图像和文字
import java.lang.reflect.Field;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.text.method.LinkMovementMethod;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.textview);
textView.setTextColor(Color.BLACK);
textView.setBackgroundColor(Color.WHITE);
textView.setTextSize(20);
String html = "图像1<img src='image1' />";
html += "图像2<img src='image2' />";
html += "图像3<a href='http://www.baidu.com' ><img src='image3' /></a>";
CharSequence charSequence = Html.fromHtml(html, new ImageGetter()
{
public Drawable getDrawable(String source)
{
//转载图像资源
Drawable drawable = getResources().getDrawable(getResourceId(source));
if (source.equals("image3"))
drawable.setBounds(0, 0, drawable.getIntrinsicWidth() / 2,drawable.getIntrinsicHeight() / 2);
else
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight() );
return drawable;
}
}, null);
textView.setText(charSequence);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public int getResourceId(String name)//name参数标识R.drawable中的图像文件名
{
try
{
Field field = R.drawable.class.getField(name);//根据资源ID的变量(也就是资源的文件名)名获取Field对象
return Integer.parseInt(field.get(null).toString());//取得并返回资源ID字段(静态变量)的值
}
catch (Exception e)
{
}
return 0;
}
} 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</RelativeLayout> 相关推荐
xfcyhades 2020-11-20
Michael 2020-11-03
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28