微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何避免在编辑文本中编辑特定字符

如何解决如何避免在编辑文本中编辑特定字符

我有一个像这样的字符串08:12:01,868-> hour:minute:second,millisecond

现在我需要进行编辑,我必须提供一个选项来编辑:的前两个字符跳过一个,然后再次允许编辑下两个字符的跳过:,依此类推。

目前,我在实现这一目标的同时还具有很多逻辑。我有四个编辑文本,然后拆分字符串,然后在4个编辑文本中加载值并进行检索。加入所有已编辑的子字符串后,我将该值保存在DB中。

还有其他更好的方法可以实现这一目标。

我的意思是只将字符串加载到一个编辑文本中,然后我应该能够锁定诸如lockFromEditChar(":",",")之类的特定字符,并且如果清除了所有字符,则可以使用认值零来编辑其余值。 / p>

有可能吗?或其他最佳选择?

解决方法

该技术称为“遮罩”。像这样创建此类MaskWatcher

import android.text.Editable;
import android.text.TextWatcher;

public class MaskWatcher implements TextWatcher {
    private boolean isRunning = false;
    private boolean isDeleting = false;
    private final String mask;

    public MaskWatcher(String mask) {
        this.mask = mask;
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence,int start,int count,int after) {
        isDeleting = count > after;
    }

    @Override
    public void onTextChanged(CharSequence charSequence,int before,int count) {
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (isRunning || isDeleting) {
            return;
        }
        isRunning = true;

        int editableLength = editable.length();
        if (editableLength < mask.length()) {
            if (mask.charAt(editableLength) != '#') {
                editable.append(mask.charAt(editableLength));
            } else if (mask.charAt(editableLength-1) != '#') {
                editable.insert(editableLength-1,mask,editableLength-1,editableLength);
            }
        }

        isRunning = false;
    }
}

,然后像这样使用您的编辑文本

editText.addTextChangedListener(MaskWatcher("##:##:##,###"));

,

如果光标停留在最后一个位置并且禁用longClick(复制粘贴):

请注意,此示例仅适用于字符串,不适用跨度

创建TextWatcher并自动添加:和,当您检测到添加的新字符并且新大小为2,4(for':'),6(for',')。

还要检测何时删除字符,并且当前大小为2,4,6,则必须删除';'之前的字符。或“,”。

class Watcher(private val textView:TextView) : TextWatcher {

    override fun onTextChanged(s: CharSequence?,start: Int,before: Int,count: Int) {
         val text = s?.toString()?:""
         val isDelete = textView.length > text.size
         if(isDelete) {
              //you can change this to an if to check for 2,6 and use take(size-1)
              newString = when(text.size) {
                  2->text.take(1)
                  4->text.take(3)
                  6->text.take(5)
              }
              if(newString!=null) {
                  textView.text = newString
              }
         } else {
              newString = when(text.size) {
                  2,4 -> text + ":"
                  6 -> text + ","
              }
              if(newString!=null) {
                  textView.text = newString
              }
         }
    }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。