android,在searchview中阻止特殊字符

时间:2017-05-15 14:07:42

标签: android filter special-characters searchview

我是一个专门用android编程的新手。 我在我的应用程序中使用SearchView但我不知道如何阻止特殊字符。 我见过有关EditText的主题,但没有关于SearchView的内容,我需要帮助。

我在App栏中使用SearchView和这个xml菜单:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/search"
        android:icon="@drawable/ic_search_white_24dp"
        android:title="@string/search_title"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always" />
</menu>

和此活动代码:

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_results);

}

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.search_option_menu, menu);

        // Associate searchable configuration with the SearchView
        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        searchView = (SearchView) menu.findItem(R.id.search).getActionView();
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}

所以我等你的答案,谢谢。

2 个答案:

答案 0 :(得分:1)

您可以检测输入字符的时间:

//In onCreate
EditText et;//initialize
et.addTextChangedListener(tw);

在onCreate之外:

private TextWatcher tw = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //If the text contains a "bad" char, (char that isn't equal to A-Z/a-z or 0-9, remove it from the edittext
    }

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

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
};

(edittext应声明为类变量)

关于检测的建议:

//s is the char sequence

String string = s.toString();
boolean found = false;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++){
    String ch = s.charAt(i) + "";//Convert to check with regex
    if(!Pattern.compile("[A-Z|a-z|0-9]").matcher(ch).find()){
        found = true;
    }else{
        sb.append(ch);
    }

}
if(found){
    editText.setText(sb.toString());//only apply the text if a special char is found
}

我对特殊字符的解释是非数字和非A-Z。可以修改此项以匹配您认为特殊的任何字符。如果您想要禁用几个字符,最好检查这些字符而不是检查它是否包含所有其他字符。

答案 1 :(得分:0)

我遇到了将“>”转换为“ |>”的问题。这就是我用Kotlin修复的方式:

override fun onQueryTextChange(newText: String?): Boolean {
    Log.w(TAG, "new text $newText")
    if (newText != null && newText.contains("|>")) {
        val text = newText?.replace("|>", ">")
        search.setQuery(text, false)
    } else {
          // do something
    }
    return false
}
相关问题