java - 具有特定模式的编辑文本

标签 java android design-patterns android-edittext

我正在尝试编写一个 EditText 字段以具有特定的模式。模式是:

P20_ _ / _ _ / _ _ _ _

我想要的是,当用户开始键入时,字符会取代下划线,但保留正斜杠。

我是初学者,但这似乎很有挑战性。

这是我到目前为止所尝试过的,它在开头给出了 P20,但字符并没有取代下划线:

editPemacNo.setText("P20__/__/____");
    Selection.setSelection(editPemacNo.getText(), editPemacNo.getText().length());


    editPemacNo.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            if(!s.toString().contains("P20")){
                editPemacNo.setText("P20__/__/____");
                Selection.setSelection(editPemacNo.getText(), editPemacNo.getText().length());

            }

        }
    });

有人可以帮助我吗?

最佳答案

我找到了解决方案:

使用这个 Android 库 - https://github.com/PaXLiCh/FormattEditText .

这是我在 XML 中使用的代码:

 <ru.kolotnev.formattedittext.MaskedEditText
                android:id="@+id/editTextPemac"
                android:layout_width="115dp"
                android:layout_height="45dp"
                android:layout_marginStart="11dp"
                android:layout_marginTop="7dp"
                android:layout_toEndOf="@+id/spinnerOptions"
                android:background="@drawable/edittext"
                android:maxLines="1"
                android:textSize="15sp"
                android:textAlignment="center"
                app:mask="P20**/**/****"
                app:placeholder="_"/>

希望这对遇到同样问题的人有所帮助!

关于java - 具有特定模式的编辑文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50924187/

相关文章:

java - Objectify:排序查询结果 ("no matching index found"错误)

java - 如何理解DIP和单例之间的冲突?

android - 适用于 Android 5.1.1 及更高版本的 Cordova 的外部存储路径(SD 卡)

java - 删除作为策略模式一部分的条件代码

java - Core Java/JSF/Servlet 中状态模式的示例是什么?

java - 我可以将tools.jar上传到Maven Central吗?

java - Map内部如何输入重复的key?

java - 是否有适用于 android 的可配置预提交 Hook 解决方案?

android - 不支持 Path.isconvex。 Android Studio 中的渲染问题

c# - UML 类图 : is this how to write abstract method and property?