Android开发(16)-TextView显示表情图像和文字

来源:互联网 发布:淘宝拍单给钱是真的吗 编辑:程序博客网 时间:2024/06/06 09:03

从这个案例中我们可以学到当我们美化图片美化界面的时候可以在某一区域输入图片和文字混搭信息,第三张图片按比例缩小,第四张图像有超链接

布局文件

<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="fill_parent"        android:layout_height="wrap_content"        android:layout_margin="10dp"        android:background="#FFF" /></RelativeLayout>


MainActivity.java

package com.example.textview3;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 {public int getResourceId(String name) {try {// 根据资源的ID的变量名获得Field的对象,使用反射机制来实现的Field field = R.drawable.class.getField(name);// 取得并返回资源的id的字段(静态变量)的值,使用反射机制return Integer.parseInt(field.get(null).toString());} catch (Exception e) {// TODO: handle exception}return 0;}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);TextView textView = (TextView) this.findViewById(R.id.textview);textView.setTextColor(Color.BLACK);textView.setBackgroundColor(Color.WHITE);textView.setTextSize(20);// 设置字体的大小String html = "图像1<img src='image1'/>图像2<img src='image2'/>图像3<img src='image3'/><p>";html += "图像4<a href='http://www.baidu.com'><img src='image4'></a>图像5<img src='image5'/>";CharSequence charSequence = Html.fromHtml(html, new ImageGetter() {@Overridepublic Drawable getDrawable(String source) {// TODO Auto-generated method stub// 获得系统资源的信息,比如图片信息Drawable drawable = getResources().getDrawable(getResourceId(source));// 第三个图片文件按照50%的比例进行压缩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());}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}


 

原创粉丝点击