Search code examples
androidfragmentandroid-softkeyboard

How to handle event soft keyboard hidden?


My note application has 2 fragments on a screen: A list of notes fragment and a note detail fragment to display the selected note in the second fragment, it has an input text field (android:inputType="textMultiLine"). As I want to handle event keyboard hidden so I can save the change user has made when they close the keyboard. Can anyone give me a clue to do this task?


Solution

  • Here's how i handle it on my Note Detail fragment:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        this.view = inflater.inflate(R.layout.fragment_note_detail_of_style_searching, container , false);
    
        listviewFilter = (ListView) view.findViewById(R.id.listview_filter);
        noteDetailView = view.findViewById(R.id.note_detail_of_style_view);
        photoDetailView = view.findViewById(R.id.gv_note_detail_photo);
    
        view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    
            @Override
            public void onGlobalLayout() {                
                int heightDiff = view.getRootView().getHeight() - view.getHeight();
                if (heightDiff > 200) { 
                    isWatchingKeyboard = true;
                    photoDetailView.setVisibility(View.GONE);
                    return; //must exit now
                }
    
                if(isWatchingKeyboard){
                    isWatchingKeyboard = false;
                    viewForFocus.requestFocus();
                    photoDetailView.setVisibility(View.VISIBLE);
                }
            }
        });
    
        return this.view;
    }