您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了“如何使用SpannableString和ImageSpan在textview中插入圖片”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“如何使用SpannableString和ImageSpan在textview中插入圖片”這篇文章吧。
先上效果圖:
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對象,即所要插入的圖片 Drawable d = getResources().getDrawable(id); d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight()); //用這個drawable對象代替字符串easy ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE); //包括0但是不包括"easy".length()即:4。[0,4)。值得注意的是當我們復制這個圖片的時候,實際是復制了"easy"這個字符串。 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); } }); } }
以上是“如何使用SpannableString和ImageSpan在textview中插入圖片”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業(yè)資訊頻道!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。