I need to uppercase all characters of Android text

2019-09-16 04:57发布

问题:

I know about using setAllCaps(true) but it requires me to use API14 as min, and I would like to keep API 9 as min, so I would like to know if anyone has found a way to capitalize all characters of all textViews in certain layout?

回答1:

One could easily extend the TextView and change the text case there manually. Example:

package com.example.allcapstextview;

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

import java.util.Locale;

public class AllCapsTextView extends TextView {
    private Locale mLocale;

    public AllCapsTextView(Context context) {
        super(context);
    }

    public AllCapsTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mLocale = context.getResources().getConfiguration().locale;
    }

    @Override
    public void onFinishInflate() {
        super.onFinishInflate();
        CharSequence text = getText();
        if (text != null) {
            text = text.toString().toUpperCase(mLocale);
            setText(text);
        }
    }
}

And use this view in layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">

    <com.example.allcapstextview.AllCapsTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>


回答2:

Alternative method is to create a class that will implement TransformationMethod. In appropriate getTransformation() you just make all letters to uppercase.

public class AllCapsTransformationMethodCompat implements TransformationMethod{

    private static AllCapsTransformationMethodCompat sInstance;

    static AllCapsTransformationMethodCompat getInstance(){
        if(sInstance == null){
            sInstance = new AllCapsTransformationMethodCompat();
        }
        return sInstance;
    }
    @Override
    public CharSequence getTransformation(CharSequence source, View view) {
        return !TextUtils.isEmpty(source)
                ? 
                source.toString().toUpperCase(view.getContext().getResources().getConfiguration().locale) 
                : 
                source;
    }

    @Override
    public void onFocusChanged(View view, CharSequence sourceText,
            boolean focused, int direction, Rect previouslyFocusedRect) {
        // TODO Auto-generated method stub

    }

}

Usage:

@SuppressLint("NewApi")
    public static void setAllCaps(TextView textView, boolean allCaps) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH){
            textView.setAllCaps(allCaps);
        }else{
            textView.setTransformationMethod(allCaps ? AllCapsTransformationMethodCompat.getInstance() : null);
        }
    }