如何在多行TextView的末尾插入ImageView?

发布于 2024-12-11 22:11:47 字数 1105 浏览 0 评论 0原文

也许这是一个愚蠢的问题,但我找不到在 TextView 第二行末尾插入小图像的方法。图像始终出现在整个文本视图的右侧,而不是行尾。

我想插入这样的图像:

TextTextTextTextTextTextTextTextTextText
TextTextTextText. <ImageView>

我得到的是:

TextTextTextTextTextTextTextTextTextText  <ImageView>
TextTextTextText. 

我希望有办法做到这一点。

来源:

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TESTESTESTESTESTESTESTESTESTESTESTESTES"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#FFFFFF" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/tv"
            android:src="@drawable/icon" />
    </RelativeLayout>

Maybe it's a stupid question, but I cant find a way to inser small image at the end of second line of TextView. Image is always appears to the right of whole textview, not the line end.

I want to insert image like this:

TextTextTextTextTextTextTextTextTextText
TextTextTextText. <ImageView>

What I am getting is:

TextTextTextTextTextTextTextTextTextText  <ImageView>
TextTextTextText. 

I hope there is way to do it.

Src:

<RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="TESTESTESTESTESTESTESTESTESTESTESTESTES"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textColor="#FFFFFF" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/tv"
            android:src="@drawable/icon" />
    </RelativeLayout>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

哑剧 2024-12-18 22:11:47

创建一个 ImageSpan 并将其添加到您的文本视图中。这样,您就可以将图像放在文本中所需的位置

示例 -

ImageSpan imagespan = new ImageSpan(appContext, ressource); 
text.setSpan(imagespan, i, i+ strLength, 0); //text is an object of TextView

create an ImageSpan and add it to your textview. This way, you can put your image where you want in the text

Example -

ImageSpan imagespan = new ImageSpan(appContext, ressource); 
text.setSpan(imagespan, i, i+ strLength, 0); //text is an object of TextView
小…楫夜泊 2024-12-18 22:11:47

完成它的一种最佳方法如下......

ImageGetter getter = new ImageGetter(){                 
    public Drawable getDrawable(String source){   // source is the resource name
        Drawable d = null;
        Integer id =  new Integer(0);
        id = getApplicationContext().getResources().getIdentifier(source, "drawable", "com.sampleproject");

        d = getApplicationContext().getResources().getDrawable(id);   

        if (d != null)
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        return d;
    }
};

String imgString = this.getResources().getString(R.string.text_string) + " <img src=\"img_drawable_image\"/>";
((TextView)findViewById(R.id.textview_id)).setText(
Html.fromHtml(imgString, getter, null));

One best way to complete it is as the following...

ImageGetter getter = new ImageGetter(){                 
    public Drawable getDrawable(String source){   // source is the resource name
        Drawable d = null;
        Integer id =  new Integer(0);
        id = getApplicationContext().getResources().getIdentifier(source, "drawable", "com.sampleproject");

        d = getApplicationContext().getResources().getDrawable(id);   

        if (d != null)
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        return d;
    }
};

String imgString = this.getResources().getString(R.string.text_string) + " <img src=\"img_drawable_image\"/>";
((TextView)findViewById(R.id.textview_id)).setText(
Html.fromHtml(imgString, getter, null));
肤浅与狂妄 2024-12-18 22:11:47

您可以将图像添加到字符串末尾,而无需使用 imageview,如下所示;

fun addImageToEndOfTheString(text: String, drawableResourceId : Int ,context: Context) : SpannableStringBuilder {
    val drawable = ContextCompat.getDrawable(context, drawableResourceId)!!
    drawable.setBounds(14, 0, 64, 50)
    val rocketImageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)

    val ssBuilder = SpannableStringBuilder(text)

    ssBuilder.setSpan(
        rocketImageSpan,
        text.length - 1,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    return ssBuilder
}

并称其为;

textView.text = addImageToEndOfTheString("Your text is here", R.drawable.ic_your_image, context!!)

You can add the image to end of the string without using imageview like below;

fun addImageToEndOfTheString(text: String, drawableResourceId : Int ,context: Context) : SpannableStringBuilder {
    val drawable = ContextCompat.getDrawable(context, drawableResourceId)!!
    drawable.setBounds(14, 0, 64, 50)
    val rocketImageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)

    val ssBuilder = SpannableStringBuilder(text)

    ssBuilder.setSpan(
        rocketImageSpan,
        text.length - 1,
        text.length,
        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    )

    return ssBuilder
}

and call it like;

textView.text = addImageToEndOfTheString("Your text is here", R.drawable.ic_your_image, context!!)

The image will placed end of the text

不再让梦枯萎 2024-12-18 22:11:47
SpannableString ss = new SpannableString(title);
Drawable d = getResources().getDrawable(R.drawable.gallery_list);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
newsTextView.setText(ss);
SpannableString ss = new SpannableString(title);
Drawable d = getResources().getDrawable(R.drawable.gallery_list);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 0, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
newsTextView.setText(ss);
恋竹姑娘 2024-12-18 22:11:47
TextView textView =new TextView(this);
SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " );
Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add );
ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1,  ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE );  
textView.setText( ssb, BufferType.SPANNABLE );
TextView textView =new TextView(this);
SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " );
Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add );
ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1,  ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE );  
textView.setText( ssb, BufferType.SPANNABLE );
走过海棠暮 2024-12-18 22:11:47

如果您想在文本末尾插入 Drawable,Drawable 会隐藏文本的最后一个字符,以避免在文本末尾添加另一个字符并从该字符开始绘制。

val myText = "Your text"    

val span: Spannable = SpannableString(myText+"-")
val android: Drawable = ContextCompat.getDrawable(this, R.drawable.yourDrawable)!!
android.setBounds(0, 0, 30, 30)
val image = ImageSpan(android, ImageSpan.ALIGN_BOTTOM)
span.setSpan(image, span.indexOf("-"), span.indexOf("-")+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)

If you want to insert Drawable at the end of the text, Drawable is hiding the last character of the text to avoid that add another character at the end of the text and start the drawable at that character.

val myText = "Your text"    

val span: Spannable = SpannableString(myText+"-")
val android: Drawable = ContextCompat.getDrawable(this, R.drawable.yourDrawable)!!
android.setBounds(0, 0, 30, 30)
val image = ImageSpan(android, ImageSpan.ALIGN_BOTTOM)
span.setSpan(image, span.indexOf("-"), span.indexOf("-")+1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
方觉久 2024-12-18 22:11:47

TextView 类上的 Kotlin 扩展

/**
 * Creates a StringSpan using the text from the TextView itself and it also adds an ImageSpan at the
 * end of the last line of the TextView.
 * This basically allows us to set a drawable at the end of the TextView text.
 */
fun TextView.setImageSpanAtTheEnd(context: Context, @DrawableRes drawableRes: Int) {
    text = SpannableString("$text ").apply {
        val d = ContextCompat.getDrawable(context, drawableRes) ?: throw RuntimeException("Drawable not found!")
        d.setBounds(0, 0, d.intrinsicWidth, d.intrinsicHeight)
        setSpan(ImageSpan(d, ImageSpan.ALIGN_BASELINE), text.length, text.length+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
    }
}

只需在 TextView 上设置文本后调用它即可。

Kotlin extension on the TextView class

/**
 * Creates a StringSpan using the text from the TextView itself and it also adds an ImageSpan at the
 * end of the last line of the TextView.
 * This basically allows us to set a drawable at the end of the TextView text.
 */
fun TextView.setImageSpanAtTheEnd(context: Context, @DrawableRes drawableRes: Int) {
    text = SpannableString("$text ").apply {
        val d = ContextCompat.getDrawable(context, drawableRes) ?: throw RuntimeException("Drawable not found!")
        d.setBounds(0, 0, d.intrinsicWidth, d.intrinsicHeight)
        setSpan(ImageSpan(d, ImageSpan.ALIGN_BASELINE), text.length, text.length+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
    }
}

Just call it after you set the text on the TextView and that's it.

憧憬巴黎街头的黎明 2024-12-18 22:11:47

这可能不是最好的解决方案,但您可以尝试使用 Html.fromHtml 将图像插入到您的行中。

ImageGetter getter = new ImageGetter(){                 
    public Drawable getDrawable(String source){
        Drawable d = null;

        context.getResources().getDrawable(Integer.parseInt(source));   

        if (d != null)
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        return d;
    }
};
String imgString = <source string> + " <img src=\"R.drawable.icon\"/>";
((TextView)findViewById(R.id.tv)).setText(
    Html.fromHtml(imgString, getter, null));

It might be not the best solution, but you can try using Html.fromHtml to insert image into your line.

ImageGetter getter = new ImageGetter(){                 
    public Drawable getDrawable(String source){
        Drawable d = null;

        context.getResources().getDrawable(Integer.parseInt(source));   

        if (d != null)
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());

        return d;
    }
};
String imgString = <source string> + " <img src=\"R.drawable.icon\"/>";
((TextView)findViewById(R.id.tv)).setText(
    Html.fromHtml(imgString, getter, null));
靖瑶 2024-12-18 22:11:47

感谢 Libin Thomas 我为 RatingBar 创建了一个解决方案。我使用了带有 SVG 星号的 SvgRatingBar

ImageSpan 扩展了 DynamicDrawableSpan,并且 DynamicDrawableSpan 只有一个子级 - ImageSpan。因此,要将另一个 View 附加到 TextView 的末尾,我们应该获得一个由 View 制成的可绘制对象。我向 SvgRatingBar 添加了一个方法 getDrawable()

public class SvgRatingBar extends AppCompatRatingBar {

    ...
    private Drawable drawable;

    public Drawable getDrawable() {
        return drawable;
    }

    private void init() {
        LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
        setProgressDrawable(drawable);
        this.drawable = drawable;
    }

创建评级布局 (layout_ rating_bar.xml):

<?xml version="1.0" encoding="utf-8"?>
<com.example.myapplication.SvgRatingBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="11dp"
    android:isIndicator="true"
    android:minHeight="13dp"
    android:numStars="5"
    android:progressDrawable="@drawable/rating_bar"
    android:rating="3.5"
    android:stepSize="0.01" />

然后编写以下代码:

val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val ratingBar: SvgRatingBar = inflater.inflate(R.layout.layout_rating_bar, null, false)
    as SvgRatingBar
ratingBar.rating = 3.5f
val drawable = ratingBar.drawable

val ss = SpannableString("dsfjdskljsf dsfjsdkljfslk dsfjlksdjflsdkjf ")
drawable.setBounds(0, 0, 170, 30) // Set width and height of the rating bar here.
val span = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
ss.setSpan(span, ss.length - 1, ss.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
textView.setText(ss)

输入图像描述这里

Thanks to Libin Thomas I created a solution for RatingBar. I used SvgRatingBar with SVG stars.

ImageSpan extends DynamicDrawableSpan, and DynamicDrawableSpan has only one child - ImageSpan. So, to attach another View to the end of the TextView we should get a drawable made from the View. I added a method getDrawable() to SvgRatingBar:

public class SvgRatingBar extends AppCompatRatingBar {

    ...
    private Drawable drawable;

    public Drawable getDrawable() {
        return drawable;
    }

    private void init() {
        LayerDrawable drawable = (LayerDrawable) createTile(getProgressDrawable(), false);
        setProgressDrawable(drawable);
        this.drawable = drawable;
    }

Create a layout for the rating (layout_rating_bar.xml):

<?xml version="1.0" encoding="utf-8"?>
<com.example.myapplication.SvgRatingBar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="11dp"
    android:isIndicator="true"
    android:minHeight="13dp"
    android:numStars="5"
    android:progressDrawable="@drawable/rating_bar"
    android:rating="3.5"
    android:stepSize="0.01" />

Then write this code:

val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val ratingBar: SvgRatingBar = inflater.inflate(R.layout.layout_rating_bar, null, false)
    as SvgRatingBar
ratingBar.rating = 3.5f
val drawable = ratingBar.drawable

val ss = SpannableString("dsfjdskljsf dsfjsdkljfslk dsfjlksdjflsdkjf ")
drawable.setBounds(0, 0, 170, 30) // Set width and height of the rating bar here.
val span = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)
ss.setSpan(span, ss.length - 1, ss.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
textView.setText(ss)

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文