如何在Android的TextView中显示图像?
我想在TextView中插入一些图像。 怎么做? 任何想法
您可以创build一个spannableString,并将您的图像放在TextView所需的位置。 或者你可以使用
ImageSpan is = new ImageSpan(context, resId); text.setSpan(is, index, index + strLength, 0);
您可以更轻松地使用API 1中的SpannableStringBuilder
用法示例:
对于API> = 21
SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append("My string. I ") .append(" ", new ImageSpan(getActivity(), R.drawable.ic_action_heart), 0) .append(" Cree by Dexode"); textView.setText(builder);
对于API> = 1
SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append("My string. I ").append(" "); builder.setSpan(new ImageSpan(getActivity(), R.drawable.ic_action_heart), builder.length() - 1, builder.length(), 0); builder.append(" Cree by Dexode"); textView.setText(builder);
ImageSpan is = new ImageSpan(context, R.drawable.arrow); SpannableString text = new SpannableString("Lorem ipsum dolor sit amet"); text.setSpan(is, 5, 5 + 10, 0);
做这样的事情。
textView.setCompoundDrawableWithIntrinsicBounds(yourImg, null, null, null);
make custom.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:id="@+id/thumbnail_view" android:src="@drawable/ic_launcher" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/message_view" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@id/thumbnail_view" android:textSize="18sp" android:text="MyText" /> </RelativeLayout>
然后在main.xml中包含这个custom.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center_horizontal"> <include android:id="@+id/customView" layout="@layout/custom"/> </LinearLayout>
这是我的mainActivity.class
package com.example.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.TextView; public class MainActivity extends Activity implements OnClickListener { private String TAG = MainActivity.class.getSimpleName(); ImageView img; ImageView img1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView txt = (TextView)findViewById(R.id.message_view); img = (ImageView) findViewById(R.id.thumbnail_view); img1 = (ImageView) findViewById(R.id.thumbnail_view1); img.setOnClickListener(this); img1.setOnClickListener(this); } @Override public void onClick(View v) { if(v== img){ // do something for img } else if (v== img1){ //do something for img1 } } }
试试这个..
<string name="home"><img src=""></img></string> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/home" />