我想能够分配一个xml属性或风格的TextView,将使它在所有大写字母的任何文本。

属性android:inputType="textCapCharacters"和android:capitalize="characters"什么都不做,看起来像他们是用户输入的文本,而不是一个TextView。

我想这样做,这样我就可以将风格从内容中分离出来。我知道我可以在程序上做到这一点,但我想再次保持风格的内容和代码。


当前回答

android:textAllCaps怎么样?

其他回答

我认为这是一个非常合理的要求,但看起来你现在不能这么做。真是彻底的失败。哈哈

更新

您现在可以使用 textAllCaps 强制所有大写。

通过在Android应用程序中使用AppCompat textAllCaps来支持旧的API(小于14)

AppCompat附带了一个名为CompatTextView的UI小部件,它是一个自定义TextView扩展,添加了对textAllCaps的支持

对于更新的android API > 14,您可以使用:

android:textAllCaps="true"

举个简单的例子:

<android.support.v7.internal.widget.CompatTextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:textAllCaps="true"/>

来源:developer.android

更新:

CompatTextView被AppCompatTextView所取代 最新appcompat-v7库~ Eugen Pechanec

PixlUI项目允许您在任何textview或textview的子类中使用textAllCaps,包括: 按钮, EditText AutoCompleteEditText 复选框 RadioButton 还有其他几个。

你需要创建你的文本视图使用pixlui版本,而不是那些从android源,这意味着你必须这样做:

<com.neopixl.pixlui.components.textview.TextView

        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        pixlui:textAllCaps="true" />

PixlUI还允许你设置一个自定义字体/字体,你把它放在你的资产文件夹。

我正在PixlUI框架的一个Gradle分支上工作,它使用Gradle并允许一个人指定textAllCaps以及来自样式的字体,而不是像原始项目那样要求它们内联。

android:textAllCaps怎么样?

我提出了一个解决方案,这是类似于RacZo的事实,我也创建了TextView的子类处理使文本大写。

不同之处在于,我没有重写setText()方法之一,而是使用了与API 14+上TextView实际做的类似的方法(在我看来,这是一个更干净的解决方案)。

如果你查看源代码,你会看到setAllCaps()的实现:

public void setAllCaps(boolean allCaps) {
    if (allCaps) {
        setTransformationMethod(new AllCapsTransformationMethod(getContext()));
    } else {
        setTransformationMethod(null);
    }
}

AllCapsTransformationMethod类(目前)不是公共的,但仍然是可用的源。我已经简化了这个类一点(删除setLengthChangesAllowed()方法),所以完整的解决方案是:

public class UpperCaseTextView extends TextView {

    public UpperCaseTextView(Context context) {
        super(context);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setTransformationMethod(upperCaseTransformation);
    }

    public UpperCaseTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        setTransformationMethod(upperCaseTransformation);
    }

    private final TransformationMethod upperCaseTransformation =
            new TransformationMethod() {

        private final Locale locale = getResources().getConfiguration().locale;

        @Override
        public CharSequence getTransformation(CharSequence source, View view) {
            return source != null ? source.toString().toUpperCase(locale) : null;
        }

        @Override
        public void onFocusChanged(View view, CharSequence sourceText,
                boolean focused, int direction, Rect previouslyFocusedRect) {}
    };
}