如果显示键盘,则Android SpellChecker无法正常工作

时间:2019-11-11 06:22:58

标签: android android-edittext android-softkeyboard android-spellcheck

我有一个简单的活动,使用SpellCheckerSession来建议单词的相似匹配。 但是如果键盘显示spellChecker则无法正常工作。 也许是因为键盘也使用了拼写检查器。

我的简化活动是:

    public class TestActivity extends AppCompatActivity  implements  SpellCheckerSession.SpellCheckerSessionListener{

    private SpellCheckerSession spellChecker;

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

        test();

    }

    void test() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                spellChecker.getSentenceSuggestions(new TextInfo[] {new TextInfo("bool")}, 4);
                test();

            }
        }, 2000);
    }

    @Override
    public void onGetSuggestions(SuggestionsInfo[] results) {}

    @Override
    public void onGetSentenceSuggestions(SentenceSuggestionsInfo[] results) {

        Log.i("tag", "results size: " + results.length);
        for (SentenceSuggestionsInfo result : results) {
            final int len = result.getSuggestionsCount();

            for (int j = 0; j < len; ++j) {
                int a = result.getSuggestionsInfoAt(j).getSuggestionsCount();
                Log.i("tag", "getSuggestionsCount : " + a);

                for (int i = 0; i < a; ++i) {
                    Log.i("tag", "Suggestion: " + result.getSuggestionsInfoAt(j).getSuggestionAt(i));
                }
            }
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        final TextServicesManager tsm = (TextServicesManager)
                getApplicationContext().getSystemService(Context.TEXT_SERVICES_MANAGER_SERVICE);
        if (tsm != null) {
            spellChecker = tsm.newSpellCheckerSession(null, Locale.US, this, true);

        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (spellChecker != null) {
            spellChecker.close();
        }
    }
}

在此活动中,我每2秒调用getSentenceSuggestions来测试其是否正常工作。 在我的活动布局中,我有一个EditText。午餐后,应用程序spellChecker工作并在logcat中显示建议,但是如果单击editText以显示键盘,spellChecker不起作用,并且getSuggestionsCount在logcat中显示-1。如果隐藏键盘,一切正常。

1 个答案:

答案 0 :(得分:0)

通过向android:inputType="textNoSuggestions|textVisiblePassword"添加EditText解决了这个问题。

另一种方法是:

EditText editText = findViewById(R.id.edit_text);
    editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

如果您使用诸如搜索栏之类的库,并且无法访问EditText视图,则可能对您有用:

EditText view = (EditText) getCurrentFocus();
            if (view != null) {
                view.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
            }