我知道使用setAllCaps(true)但它要求我使用API14作为min,我想将API 9保持为min,所以我想知道是否有人找到了一种方法来大写所有字符textViews在某种布局?
答案 0 :(得分:1)
可以轻松扩展TextView
并手动更改文本案例。例如:
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);
}
}
}
在布局中使用此视图:
<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>
答案 1 :(得分:0)
替代方法是创建一个将实现TransformationMethod的类。在适当的getTransformation()
中,您只需将所有字母都设为大写。
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
}
}
用法:
@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);
}
}