Search code examples
javaandroidandroid-edittextfragment

Android EditText.setHint not working in fragment


I have a fragment for the sliding menu I implemented and I encountered a problem with the EditText I am using in it. Unfortunately, whenever I type something into the EditText in my sliding menu, the hint is still shown. Therefore I tried to find a workaround, so I basically set the hint to nothing if nothing is in the EditText, but that does not work at all. The other code, that enables or disables a button based on the text, does work though. It's a mystery to me.

What it's doing:

https://i.sstatic.net/9DEPN.png

My workaround:

public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        dbHandler = new DatabaseHandler(getActivity());

        final Button addBtn = (Button) getView().findViewById(R.id.btnAddPlaylist);
        final EditText txtPlaylistName = (EditText) getView().findViewById(R.id.txtPlaylist);

        txtPlaylistName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                boolean hasContent = !String.valueOf(s).trim().isEmpty();

                addBtn.setEnabled(hasContent);
                txtPlaylistName.setHint((hasContent) ? "Create new Playlist..." : "");
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

Solution

  • you have to call setHint with the string if your EditText is empty, not if it contains text. In your snippet, you have:

    txtPlaylistName.setHint((hasContent) ? "Create new Playlist..." : "");
    

    which set a hint even tough you still have some content,

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
           boolean hasContent = (count != 0);
           addBtn.setEnabled(hasContent);
           txtPlaylistName.setHint((hasContent) ? null : "Create new Playlist...");
     }