【问题标题】:Capitalize first letter of TextView in an Android layout xml fileAndroid布局xml文件中TextView的首字母大写
【发布时间】:2013-09-08 13:50:00
【问题描述】:

我在布局 xml 文件中有一个 TextView,如下所示:

<TextView
   android:id="@+id/viewId"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@string/string_id" />

我的字符串是这样指定的:

<string name="string_id">text</string>

是否可以使其显示“文本”而不​​是“文本”无需 java 代码
(并且也不改变字符串本身)

【问题讨论】:

  • 不,这是不可能的。不过,您可以创建一个自定义 TextView,它将文本大写。
  • 如果我的回答回答了您的问题,您能否检查一下我的回答是否正确?

标签: android textview capitalize


【解决方案1】:

没有。但是您可以创建一个简单的 CustomView 扩展 TextView 覆盖 setText 并将第一个字母大写,正如 Ahmad 所说的那样,并在您的 XML 布局中使用它。

import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;

public class CapitalizedTextView extends TextView {

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        if (text.length() > 0) {
            text = String.valueOf(text.charAt(0)).toUpperCase() + text.subSequence(1, text.length());
        }
        super.setText(text, type);
    }
}

【讨论】:

  • 是的,这是我已经在使用的解决方案。我想知道是否有人有一个棘手的技巧可以直接在 xml 中进行操作 :) 但我想这确实是不可能的 :(
  • 是的,您必须进行简单的修改,这有点令人沮丧,但您不能指望它们能够使一切变得简单:P 虽然能够使用 Java 会很酷xml 中的函数,因此您可以说诸如 capitalize('text') 之类的内容,并将 capitalize 定义为 java 代码中的函数。
【解决方案2】:

我使用Hyrum Hammon 的答案设法将所有单词大写。

public class CapitalizedTextView extends TextView {

    public CapitalizedTextView( Context context, AttributeSet attrs ) {
        super( context, attrs );
    }

    @Override
    public void setText( CharSequence c, BufferType type ) {

        /* Capitalize All Words */
        try {
            c = String.valueOf( c.charAt( 0 ) ).toUpperCase() + c.subSequence( 1, c.length() ).toString().toLowerCase();
            for ( int i = 0; i < c.length(); i++ ) {
                if ( String.valueOf( c.charAt( i ) ).contains( " " ) ) {
                    c = c.subSequence( 0, i + 1 ) + String.valueOf( c.charAt( i + 1 ) ).toUpperCase() + c.subSequence( i + 2, c.length() ).toString().toLowerCase();
                }
            }
        } catch ( Exception e ) {
            // String did not have more than + 2 characters after space.
        }
        super.setText( c, type );
    }

}

【讨论】:

    【解决方案3】:

    作为 Kotlin 扩展函数

     fun String.capitalizeFirstCharacter(): String {
            return substring(0, 1).toUpperCase() + substring(1)
        }
    
    textview.text = title.capitalizeFirstCharacter()
    

    【讨论】:

      【解决方案4】:

      在活动中试试这个代码:

      String userName = "name";
      String cap = userName.substring(0, 1).toUpperCase() + userName.substring(1);
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-17
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 2011-11-13
        • 2021-07-29
        • 2011-05-14
        相关资源
        最近更新 更多