【问题标题】:How to horizontally scroll textview automatically with any text length?如何以任何文本长度自动水平滚动文本视图?
【发布时间】:2021-07-02 22:04:08
【问题描述】:

我想让我的文本视图自动滚动,即使没有太多的文本可以放入屏幕。我也没有找到任何可以水平滚动 textview 的库,只能垂直滚动。

我创建了我的文本视图,这是我的 xml 代码:

<TextView
        android:id="@+id/ticker"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="My text"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:ellipsize="marquee"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:textColor="@color/black"
        android:textSize="22sp" />

在我的活动中我使用:

TextView ticker = findViewById(R.id.ticker);
ticker.setSelected(true);

主要的是,如果文本长度大于可以适合屏幕的长度,文本会滚动,但我需要使用任何文本进行滚动。有什么建议吗?

【问题讨论】:

    标签: java android xml kotlin textview


    【解决方案1】:

    如果TextView 没有填满宽度,唯一的办法就是调用这个方法并将TextView 传递给它。

        fun addMarquee(textView: TextView) {
        textView.viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                val pixels = textView.measuredWidth - 1
                val params = textView.layoutParams
                params.width = pixels
                textView.layoutParams = params
                textView.isSelected = true
                textView.ellipsize = TextUtils.TruncateAt.MARQUEE
                textView.isSingleLine = true
                textView.marqueeRepeatLimit = -1
                textView.viewTreeObserver.removeOnGlobalLayoutListener(this)
            }
        })
    }
    

    注意:此方法仅在 textView 宽度为 wrap_content 时有效。

    【讨论】:

      【解决方案2】:

      您必须测量屏幕重量并像选框一样放置动画。 解决方法请参考以下链接。

      https://stackoverflow.com/a/16371310/9121785

      【讨论】:

        【解决方案3】:
        <HorizontalScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TextView 
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:scrollHorizontally="true"
                android:text="This is an Example of Horizontal TextView Scrolling This is an Example of Horizontal TextView Scrolling This is an Example of Horizontal TextView Scrolling"/></HorizontalScrollView>
        

        上面的代码将帮助您使 textview scollable

        【讨论】:

          猜你喜欢
          • 2021-10-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-01
          • 1970-01-01
          相关资源
          最近更新 更多