android 更改文本输入编辑文本提示样式

f4t66c6m  于 2023-11-15  发布在  Android
关注(0)|答案(2)|浏览(118)

我想更改TextInputEditText类型FilledBox
当之前输入提示需要样式粗体和颜色#FF0000(红色)当之后输入提示样式常规和颜色#000000(黑色)
我该怎么办

tquggr8v

tquggr8v1#

正如Martin所建议的,在EditText上使用textWatcher并覆盖onTextChange来检测EditText中的更改。
. app\src\main\assets\arial.ttf

. app\src\main\assets\arialbold.ttf

//within your Activity: 
Context context = getApplicationContext();
int colorRed = context.getResources().getColor(R.color.red, null);
int colorBlack = context.getResources().getColor(R.color.black, null);

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);
EditText tv_input               = findViewById(R.id.tv_input);

textInputLayout.setTypeface(
    Typeface.createFromAsset(context.getAssets(), "arialbold.ttf"));

ColorStateList colorStateListRed = ColorStateList.valueOf(colorRed);
ColorStateList colorStateListBlack = ColorStateList.valueOf(colorBlack);

tv_input.addTextChangedListener(new TextWatcher() {

    @Override
    public void beforeTextChanged(CharSequence s, int start, 
    int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, 
    int before, int count) {

        if(s.length() > 0){
            textInputLayout.setDefaultHintTextColor(colorStateListBlack);
            textInputLayout.setTypeface(
                Typeface.createFromAsset(
                    context.getAssets(), "arial.ttf")
            );
        }

        else{
            textInputLayout.setDefaultHintTextColor(colorStateListRed);
            textInputLayout.setTypeface(
                Typeface.createFromAsset(
                    context.getAssets(),"arialbold.ttf")
            );
        }
    }

    @Override
    public void afterTextChanged(Editable s) {}
});

layout xml:
<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/textInputLayout"
    android:hint="@string/name"
    android:textColorHint="@color/red"
    android:layout_width="match_parent"
    android:layout_height="65dp">

    <com.google.android.material.textfield.TextInputEditText
        android:id="@+id/tv_input"
        android:textColor="@color/black"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:inputType="text"
        android:textColorHint="@color/red"
        android:textSize="16sp" />
</com.google.android.material.textfield.TextInputLayout>

字符串
结果:

ctehm74n

ctehm74n2#

也许你需要在你的EditText.onTextChange函数中设置一个textWatcher并设置你的样式。

相关问题