如何在editText中检测特定字符的文本?

ano*_*ous 0 android android-edittext

我是android的完全初学者所以请原谅我,如果我的问题是愚蠢的.基本上我想要检测的是#的意思,例如,如果用户输入abc #hello则只会#hello在文本更改中被烘烤.所以我试图从github代码中获取引用并且能够打印所有#标签,但是我想要只覆盖当前标签意味着如果用户正在键入,abc #hello #hi #bye //here current tag is #bye那么我想只将当前标签干杯到飞行中出现的空间.我想知道如何修改我的代码以获得所需的结果.

码:

editTxt.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)
            showTags(s);
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    });


   //Methods
    private void showTags(CharSequence text) {

    int startIndexOfNextHashSign;

    int index = 0;
    while (index < text.length()-  1){
        sign = text.charAt(index);
        int nextNotLetterDigitCharIndex = index + 1; // we assume it is next. if if was not changed by findNextValidHashTagChar then index will be incremented by 1
        if(sign=='#'){
            startIndexOfNextHashSign = index;

            nextNotLetterDigitCharIndex = findNextValidHashTagChar(text, startIndexOfNextHashSign);
            Toast.makeText(this,text.subSequence(startIndexOfNextHashSign,nextNotLetterDigitCharIndex),Toast.LENGTH_LONG).show();
            //setColorForHashTagToTheEnd(startIndexOfNextHashSign, nextNotLetterDigitCharIndex);
        }

        index = nextNotLetterDigitCharIndex;
    }
}


private int findNextValidHashTagChar(CharSequence text, int start) {

    int nonLetterDigitCharIndex = -1; // skip first sign '#"
    for (int index = start + 1; index < text.length(); index++) {

        char sign = text.charAt(index);

        boolean isValidSign = Character.isLetterOrDigit(sign) || mAdditionalHashTagChars.contains(sign);
        if (!isValidSign) {
            nonLetterDigitCharIndex = index;
            break;
        }
    }
    if (nonLetterDigitCharIndex == -1) {
        // we didn't find non-letter. We are at the end of text
        nonLetterDigitCharIndex = text.length();
    }

    return nonLetterDigitCharIndex;
}
Run Code Online (Sandbox Code Playgroud)

Github项目

And*_*Doe 5

试试这个吧

String sampleText = "abc #hello #hi #bye";
String[] wordSplit = sampleText.split(" ");

for (int i = wordSplit.length-1; i >= 0; i--){
   if(wordSplit[i].contains("#")){
        Toast.makeText(getContext(), wordSplit[i].substring(wordSplit[i].indexOf("#")), Toast.LENGTH_SHORT).show();
        break;
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:尝试使用此而不是indexOf

lastIndexOf("#")
Run Code Online (Sandbox Code Playgroud)