Search code examples
androidandroid-tvleanback

hide keyboard from remote's back button in android TV Leanback


I was trying to hide the keyboard when the back button is pressed but its actually going back to previous menu when the back button is pressed. What I have is a simple activity with SupportSearchFragment.

public class SearchActivity extends LeanbackActivity {
    private SearchFragment mFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        mFragment = (SearchFragment) getSupportFragmentManager()
                .findFragmentById(R.id.search_fragment);
    }

    @Override
    public boolean onSearchRequested() {
        mFragment.startRecognition();
        return true;
    }
}

The fragment is

public class SearchFragment extends SearchSupportFragment
        implements SearchSupportFragment.SearchResultProvider {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setSearchResultProvider(this);

    }

    @Override
    public ObjectAdapter getResultsAdapter() {
        return null;
    }

    @Override
    public boolean onQueryTextChange(String newQuery) {
        loadQuery(newQuery);
        return true;
    }

    @Override
    public boolean onQueryTextSubmit(String query) {
        loadQuery(query);
        return true;
    }
}

What I am looking for is, once the back button is pressed, it should hide the keyboard and then another press of back button, it should go to the previous menu.

What I have found is if the ArrayObjectAdapter has any items to show, then back button directly takes to the previous menu. However, if there is no item, it hides the keyboard.

Any suggestion? Thanks in Advance.


Solution

  • First override onBackPressed ,ref

    override fun onBackPressed(){
        if( view.keyboardIsVisible() )
            this.hideKeyboard()
        else  
            super.onBackPressed();  // optional depending on your needs
    }
    

    Implement your KeyIsVisible() , ref

    fun View.keyboardIsVisible() = WindowInsetsCompat
            .toWindowInsetsCompat(rootWindowInsets)
            .isVisible(WindowInsetsCompat.Type.ime())
    

    and Hide Keyboard by

    /**
     * Use only from Activities, don't use from Fragment (with getActivity) or from Dialog/DialogFragment
     */
    fun Activity.hideKeyboard() {
        val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        val view = currentFocus ?: View(this)
        imm.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
    }
    

    Ps , It was too late when I saw your language is java , I have attached refs which will help you converting .