【问题标题】:how can i count the character limit of TextView?我如何计算TextView的字符限制?
【发布时间】:2019-12-02 06:54:18
【问题描述】:

我想计算 TextView 可以容纳的字符总数,文本大小为 14dp,宽度为 100dp,高度为 100dp。那么我必须将这些字符的限制添加到 EditText。

 <TextView
                android:id="@+id/OFSO_text1"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_weight="1"
                android:layout_gravity="top|center"
                android:fontFamily="@font/lato_bold"
                android:gravity="center|bottom"
                android:text="SEASONAL DISCOUNT ARE HERE"
                android:textAlignment="center"
                android:textAllCaps="true"
                android:textColor="@color/lightcream"
                android:textSize="14dp"
                android:textStyle="normal"
                android:autoSizeTextType="none"
               />

我已尝试过此代码,但无法正常工作。这为我提供了更多的字符限制,然后这个 Textview 可以容纳。

            TextPaint paint = textView.getPaint();
            int wordwidth=(int)paint.measureText("a",0,1);
            int screenwidth = getResources().getDisplayMetrics().widthPixels;
            int  maxLength = screenwidth/wordwidth;

请帮帮我!!提前致谢。 编码愉快!!!

【问题讨论】:

  • 试试 OFSO_text1.getText().toString().length();并将其存储到变量中
  • TextSize 应该在 SP ..
  • 这能回答你的问题吗? Limit the Length of TextView
  • @Niceumang 我不想计算字符串字符,我想向这个 TextView 添加更多文本,但在此之前,我需要知道这个文本视图可以容纳多少个字符?明白我的意思了吗?

标签: android android-layout textview android-edittext


【解决方案1】:

您的测量结果中缺少字体大小和字体。

        // In case you are storing your font in res/font
        Typeface typeface = ResourcesCompat.getFont(context, R.font.noto_sans_regular);
        paint.setTypeface = typeface
        paint.setTextSize = sizeOfYourFontInPixels

【讨论】:

  • 据我了解,您的代码是 - lato_bold R.font. lato_bold
  • 仍然计数超过 textview 限制的字符
【解决方案2】:

首先,您的文本框大小因设备而异, 对于计数,您可以执行以下操作,

    int textLenght = yourtText.getText().toString().lenght();
    if(textLenght>n) {
    yourEditText.setText(yourText);}

【讨论】:

  • 不!我想计算有多少字符,一个文本视图可以容纳特定的高度和宽度
  • 查看我最近的回答
【解决方案3】:

测量文本:你可以这样做:

float textWidth = textView.getPaint().measureText(textView.getText().toString());

if(textView.getMeasureWidth() == n) {

Log.i("Text_count",textView.getText().toString().lenght());

}

if(textWidth == n) {
Log.i("Text_count",textView.getText().toString().lenght());
}

【讨论】:

    【解决方案4】:

    试试这个

    1. 在编辑文本中添加addTextChangedListener 以读取字符。
    2. 在覆盖方法beforeTextChangedonTextChangedafterTextChanged 中,读取如下字符

      int length = etText.length();
      int leftCharacters = 500 - length; //let default length of edittext is 500
      

    希望,它对你有用!!

    【讨论】:

      猜你喜欢
      • 2012-02-27
      • 1970-01-01
      • 2019-06-20
      • 1970-01-01
      • 2019-12-05
      • 1970-01-01
      • 2012-06-12
      • 2017-02-08
      • 1970-01-01
      相关资源
      最近更新 更多