从 EditText 检查 String 上的第一个 Char

Check first Char on String from EditText

我想从 EditText 中读取一个字符串。此字符串是一个主题标签,应以# 开头。所以我想在用户输入后检查字符串的第一个字符。如果字符串未通过检查,我想给出一个简单的 Alert 并将焦点重新放在输入上,以便用户可以再次尝试输入。

我该如何实现?

您可以通过获取 ist 字符串上下文来检查编辑文本... 这可以通过调用方法 getTExt 并从结果字符串中验证开始处的字符(索引 0)

EditText myInput =....
if(myInput.getText().charAt(0) !='#'){
    //modal dialog and/ or toast!
} else {
    // ok
}

我找到了解决我问题的方法。起初我写了一个方法,检查字符串的第一个字符,如果第一个字符不等于,则发出警报,并且 return 一个布尔值。

public boolean checkFirstChar (String s, char c) {
    boolean isConform = false;
    if (s.charAt(0) != c ) {
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(SettingsActivity.this);
        // set title
        alertDialogBuilder.setTitle("Input not conform!");
        // set dialog message
        alertDialogBuilder
                .setMessage("Your hashtag should start with " + c)
                .setCancelable(false)
                .setNegativeButton("OK",new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,int id) {
                        // if this button is clicked, just close
                        // the dialog box and do nothing
                        dialog.cancel();
                    }
                });

        // create alert dialog
        AlertDialog alertDialog = alertDialogBuilder.create();

        // show it
        alertDialog.show();
    } else {
        isConform = true;
    }
    return isConform;
}

然后我做了一个确定按钮。在按钮上,我实现了一个 OnClicklistener。 OnClick 我从 EditText 中获取字符串。然后我将字符串放入方法中以检查第一个字符。如果方法 return 为真,我保存设置并开始下一个 Activity。如果没有,我 return 编辑到 EditText 焦点。

//set onClickListener on OK Button
    btn_ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //get selected Item from Spinner HashTag Item
            strgHashtag = spinner_hashtag.getSelectedItem().toString();

            //get String form EditText addHashTag
            strgAddHashtag = edit_addHashTag.getText().toString();

            //check if the first char == #
            if (checkFirstChar(strgAddHashtag, '#') == true ) {

                //if true, add String to HashTagItem List
                spinner_HashTagItems.add(strgAddHashtag);

                //save settings into a JSON File on SD-Card
                saveSettings();

                //and put the hashTagString into an IntenExtra for the HomeActivity
                Intent intent = new Intent(SettingsActivity.this, HomeActivity.class);
                intent.putExtra("hashTag", strgHashtag);
                startActivity(intent);
                finish();
                //if the char != '#'
            } else {
                //return to the user input
                edit_addHashTag.requestFocus();
            }
        }
    });

希望这段代码可以帮助其他社区成员解决同样的问题。