在android中的TextView上调整背景到文本

时间:2010-11-30 11:25:20

标签: android background textview

我想知道是否有人可以帮助我。

我有一个textView,我希望背景只是应用于文本,根据它的大小,而不是整个textView。

当文本只有一行长度时没有问题,但是当它需要多行时......

也许这张照片有助于理解这一切...

顶部:我有什么 底部:我想要什么

alt text

谢谢: - )

4 个答案:

答案 0 :(得分:3)

尝试使用以下内容:

TextView tv = (TextView) findViewById(R.id.myid);
tv.setText(Html.fromHtml("<span style="background: red;">Text</span>"));

它可能会解决您的问题......

编辑:

我在这里找到了解决方案:Set color of TextView span in Android使用SpannableString

答案 1 :(得分:1)

使用HTML span标记对我不起作用。试试这个运行代码:

String str = "This is highlighted text";
TextView textview = (TextView) findViewById (R.id.textview);
SpannableStringBuilder style = new SpannableStringBuilder (str);
style.setSpan (new BackgroundColorSpan (Color.RED), 0, str.lenght(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textview.setText(style);

答案 2 :(得分:0)

这对我有用

TextView tv = (TextView) findViewById(R.id.tvMyText); tv.setText("Some Text"); tv.setBackgroundColor(Color.CYAN);

答案 3 :(得分:0)

我采用了this解决方案,并添加了自动重力管理。初始解仅适用于起始/左重力。显示的版本支持Gravity.STARTGravity.END以及LTR和RTL检测。

这是我在Kotlin中的更新版本:

     /*
 * When trying to put a background color on the text only within textview, there is no padding. This
 * class allows a padding in this circumstance. The source is linked below.
 * Was edited by Maxime, to add a gravity switcher because the default code in the source is only working for gravity start
 * Source: https://medium.com/@tokudu/android-adding-padding-to-backgroundcolorspan-179ab4fae187
 *
 */
class PaddingBackgroundColorSpan(private val mBackgroundColor: Int, private val mPadding: Int, private val gravity: Int) : LineBackgroundSpan {
    private val backgroundRect = Rect()

    override fun drawBackground(c: Canvas, p: Paint, left: Int, right: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, lnum: Int) {
        val textWidth = Math.round(p.measureText(text, start, end))
        val paintColor = p.color

        val finalTop = top - if (lnum == 0) mPadding / 2 else -(mPadding / 2)
        val finalBottom = bottom + mPadding / 2
        val isLeftToRight = TextUtils.getLayoutDirectionFromLocale(Locale.getDefault()) == View.LAYOUT_DIRECTION_LTR
        // Draw the background
        backgroundRect.set(when {
            gravity == Gravity.LEFT || (isLeftToRight &&  gravity == Gravity.START) || (!isLeftToRight &&  gravity == Gravity.END) -> getLeftRect(left, finalTop, right, finalBottom, textWidth)
            gravity == Gravity.CENTER -> getCenterRect(left, finalTop, right, finalBottom, textWidth)
            gravity == Gravity.RIGHT || (isLeftToRight &&  gravity == Gravity.RIGHT) || (!isLeftToRight &&  gravity == Gravity.START) -> getRightRect(left, finalTop, right, finalBottom, textWidth)
            else -> {
                getLeftRect(left, finalTop, right, finalBottom, textWidth)
            }
        })

        p.color = mBackgroundColor
        c.drawRect(backgroundRect, p)
        p.color = paintColor
    }

    /**
     * Method to process the rectangle where the background (with its padding) will be drawn when the
     * text gravity left
     * @param left - left coordinate of the textView relative to its parent
     * @param top - top coordinate of the textView relative to its parent
     * @param right - right coordinate of the textView relative to its parent
     * @param bottom - bottom coordinate of the textView relative to its parent
     * @param textWidth - the width of the textView
     *
     * @return Rect - containing the coordinates to draw the background
     */
    private fun getLeftRect(left: Int, top: Int, right: Int, bottom: Int, textWidth: Int): Rect {
        return Rect(left - mPadding, top, left + textWidth + mPadding, bottom)
    }

    /**
     * Method to process the rectangle where the background (with its padding) will be drawn when the
     * text gravity right
     * @param left - left coordinate of the textView relative to its parent
     * @param top - top coordinate of the textView relative to its parent
     * @param right - right coordinate of the textView relative to its parent
     * @param bottom - bottom coordinate of the textView relative to its parent
     * @param textWidth - the width of the textView
     *
     * @return Rect - containing the coordinates to draw the background
     */
    private fun getRightRect(left: Int, top: Int, right: Int, bottom: Int, textWidth: Int): Rect {
        return Rect(right - textWidth - mPadding, top, right + mPadding, bottom)
    }

    /**
     * Method to process the rectangle where the background (with its padding) will be drawn when the
     * text gravity is center
     * @param left - left coordinate of the textView relative to its parent
     * @param top - top coordinate of the textView relative to its parent
     * @param right - right coordinate of the textView relative to its parent
     * @param bottom - bottom coordinate of the textView relative to its parent
     * @param textWidth - the width of the textView
     *
     * @return Rect - containing the coordinates to draw the background
     */
    private fun getCenterRect(left: Int, top: Int, right: Int, bottom: Int, textWidth: Int): Rect {
        val diff = abs((right - left) / 2 - textWidth / 2)
        return Rect(left + diff - mPadding, top, right - diff + mPadding, bottom)
    }
}

以及如何使用它:

private fun setBackgroundToTextOnlyInTextView(textView: TextView, text: CharSequence, @ColorRes backgroundColor: Int, @DimenRes paddingID: Int) {
    val padding = context.resources.getDimensionPixelSize(paddingID)

    textView.setShadowLayer(padding.toFloat() , 0.0f, 0.0f, Color.TRANSPARENT )
    textView.setPadding(padding, padding, padding, padding)

    val color = ContextCompat.getColor(context, backgroundColor)
    val spannableString = SpannableString(text)
    val backgroundSpan = PaddingBackgroundColorSpan(color, padding, textView.gravity)
    spannableString.setSpan(backgroundSpan, 0, spannableString.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
    textView.text = spannableString
}