默認(rèn)的TextView是無(wú)法顯示圖片的。所以想要實(shí)現(xiàn)這個(gè)功能得需要我們自己為其添加一個(gè)方法。
在這里我們采用SpannableString和ImageSpan兩個(gè)類來(lái)實(shí)現(xiàn)這一功能。
先上效果圖:

main.xml布局文件。我們使用自己定義的EditText
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <easy.stu.MyTextView android:id="@+id/mytext" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/myButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="insert" /></LinearLayout>
MyEditText.java
package easy.stu;import android.content.Context;import android.graphics.drawable.Drawable;import android.text.Spannable;import android.text.SpannableString;import android.text.style.ImageSpan;import android.util.AttributeSet;import android.widget.EditText;public class MyTextView extends TextView { public MyTextView(Context context) { super(context); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); } public void insertDrawable(int id) { final SpannableString ss = new SpannableString("easy"); //得到drawable對(duì)象,即所要插入的圖片 Drawable d = getResources().getDrawable(id); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); //用這個(gè)drawable對(duì)象代替字符串easy ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); //包括0但是不包括"easy".length()即:4。[0,4)。值得注意的是當(dāng)我們復(fù)制這個(gè)圖片的時(shí)候,實(shí)際是復(fù)制了"easy"這個(gè)字符串。 ss.setSpan(span, 0, "easy".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE); append(ss); }}MyActivity.java
package easy.stu;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MyActivity extends Activity { /** Called when the activity is first created. */ Button b; MyEditText e; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); b = (Button) findViewById(R.id.myButton); e = (MytextView) findViewById(R.id.mytext); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { e.insertDrawable(R.drawable.easy); } }); }}以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注