【问题标题】:Adjust background to text on TextView in android在android中的TextView上将背景调整为文本
【发布时间】:2011-05-17 19:47:52
【问题描述】:

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

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

文本只有一行长度的时候没有问题,但是超过一行的时候……

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

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

谢谢你:-)

【问题讨论】:

    标签: android background textview


    【解决方案1】:

    尝试使用类似的东西:

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

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

    编辑:

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

    【讨论】:

    • 谢谢 Mikpa :-) 但它不起作用,正如文档中所说的“TextView 不接受类似 HTML 的格式”,但你给了我关于使用 的想法,所以我使用 SpannableString 找到了这个:stackoverflow.com/questions/3282940/…
    【解决方案2】:

    使用 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);
    

    【讨论】:

      【解决方案3】:

      这对我有用

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

      【讨论】:

        【解决方案4】:

        我采用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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-05
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多