How to make a listener when a user start typing?

你离开我真会死。 提交于 2020-01-06 19:10:15

问题


I am designing a chat application using android studio and fire-base and got stock on how to make a listener like if the user is typing on the edit-text field The value of the user on fire-base will changed into true and when the user is not typing the value will become false.? I am looking for this solution for about a week, and didn't find any answer regarding on my researches.

How to put TextWatcher?

public class MainActivity extends AppCompatActivity{


private EditText editText;
private ListView listView;


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

    counter = 0;
    Firebase.setAndroidContext(this);
    final Firebase firebase = new Firebase("https://samp-is.firebaseio.com/");


    editText = (EditText) findViewById(R.id.editText);
    listView = (ListView) findViewById(R.id.listView);

    listView.setAdapter(new MessageAdapter(this, Message.class, R.layout.fragment_message, firebase.child("chat")));

    Button button = (Button) findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            counter++;

            Message message = new Message();

            message.setMessage(editText.getText().toString());
            editText.setText("");
            message.setAuthor("Name");
            message.setCounter(counter);
            firebase.child("chat").push().setValue(message);


        }
        });
    }
}

回答1:


Are you looking for onTextChanged(CharSequence s, int start, int before, int count)?

Quoting from the TextWatcher

This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.

This event will fired one user entered something into EditText.




回答2:


You can add textwatcher like this:

your_edit_text_name.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) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});

And capture your typing event in onTextChanged method. Hope this helps



来源:https://stackoverflow.com/questions/33794898/how-to-make-a-listener-when-a-user-start-typing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!