【问题标题】:Add drawable in resources string.xml在资源string.xml中添加drawable
【发布时间】:2019-10-21 15:07:49
【问题描述】:

我正在尝试在资源 string.xml 中的字符串 (my_string_name) 中添加可绘制对象 (ic_myimage)

<resources>
    <string name="my_string_name">Here is my image: @drawable/ic_myimage It looks great</string>
</resources>

这可能吗?我希望将带有其余字符串的图像显示在我的 TextView 中。 (代码如下)

<TextView
        android:id="@+id/myTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/my_string_name"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

注意:我尝试了在另一篇文章中找到的以下方法,但没有成功

<string name="my_string_name">Here is my image: [img src=ic_myimage/] It looks great</string>

我正在使用 Android Studio 和 Kotlin。

【问题讨论】:

    标签: android android-drawable android-resources


    【解决方案1】:

    您可以通过使用 Spannable 字符串提供文本来做到这一点

    //your drawable    
    ImageSpan is = new ImageSpan(context, R.drawable.arrow);
    
    //your spannable text "Lorem.... amet"
    SpannableString spannableText= new SpannableString("Lorem ipsum dolor sit amet");
    
    //apply image to spannable text 
    //0 is the flag
    //start and end are the index length where you wantg to put the image
    spannableText.setSpan(is, startIndex, End index, 0);
    
    //then, you can  apply this tspannable text to textview
    yourTextView.setText(spannableText);
    

    【讨论】:

    • 这是解决我的问题的最接近的答案。谢谢!我还为那些想要 Kotlin 版本的人更改了它。 val imageSpan = ImageSpan(applicationContext,R.drawable.ic_myimage ) val spannableText = SpannableString("Here is my image: ic_myimage It looks great") val keyword = "ic_myimage" val index = spannableText.indexOf(keyword); spannableText.setSpan(imageSpan, index, index + keyword.length, 0) myTextView.text = spannableText
    【解决方案2】:

    很抱歉,图片不可能在 Textview 中显示,从 drawable 调用图片的正确方法是使用 ImageView。

    喜欢这个。

    <ImageView
                android:id="@+id/imageView"
                android:layout_width="match_parent"
                android:layout_gravity="center"
                android:layout_height="200dp"
                android:layout_marginStart="30dp"
                android:layout_marginTop="8dp"
                android:layout_marginEnd="25dp"
                android:scaleType="centerInside"
                android:layout_marginLeft="100dp"
                android:layout_marginRight="8dp"
                android:background="@drawable/ic_myimage">
    
    </ImageView>
    

    【讨论】:

    • 感谢您的回复。但我想在同一个文本视图中添加几个图像,加上一些字符串。
    【解决方案3】:

    请使用文本视图的 drawableStart() 方法在文本视图左侧显示图标。但您不能将图标用作字符串文本。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多