【问题标题】:Android Clip/Cut off characters in TextViewAndroid 剪辑/截断 TextView 中的字符
【发布时间】:2017-10-27 12:16:16
【问题描述】:

我在 GridLayout 中有一个文本视图作为单行。它应该填满整个屏幕的宽度。

所以当我点击一个按钮时,我会在文本视图中添加一个新字符term.append(String.valueOf(value));term是文本视图。

但是没有剪辑,这意味着我可以在文本视图中填充很多字符,而不是 TexView 的实际大小。我想在 textview 满后停止添加字符。或者我可以水平滚动,但这也不起作用。

我尝试了以下代码:

Paint p = new Paint();
if (term.getMaxWidth() > p.measureText(term.getText().toString()))
                term.append(String.valueOf(value));

但是 term.getMaxWidth() 的值(与 LayoutParams().width 相同)太高了。

这是我的风格 xml:

<GridLayout
    android:layout_width="368dp"
    android:layout_height="495dp"
    android:layout_marginTop="8dp"
    android:columnCount="4"
    android:alignmentMode="alignMargins"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginLeft="16dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="16dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    android:foregroundGravity="center"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0">


    <TextView
        android:id="@+id/textView3"
        android:layout_width="355dp"
        android:maxWidth="355dp"
        android:layout_height="62dp"
        android:layout_columnSpan="4"
        android:text="@string/calc_term"
        android:textSize="30sp"
        android:maxLines="1"
        android:scrollHorizontally="false"
        android:isScrollContainer="false"
        android:ellipsize="start" />

谢谢

【问题讨论】:

    标签: java android xml textview


    【解决方案1】:

    试试这样:

    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:minWidth="300dp"
    

    【讨论】:

    • 对我不起作用。新字符仍会附加到 TextView。
    【解决方案2】:

    好的,我自己找到了解决方案: Paint 对象不知道文本的缩放。 因此我需要使用 TextViews 自己的 Paint 对象。

    TextPaint paint = term.getPaint();
                if (term.getWidth() > paint.measureText(term.getText().toString())
                                            + paint.measureText(String.valueOf(value)))
                    term.append(String.valueOf(value));
    

    成功了。其中value是新角色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      相关资源
      最近更新 更多