Search code examples
javaandroidchatonkeylistener

creating a chat activity in android


  1. After declaring and creating the textWatcher object, I would like to disable the send button and set it to gray if the chatText (edit text) is empty
  2. I think it's a problem of ranking. Please help.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
    
        list = (ListView)findViewById(R.id.listView);
        list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        chatText = (EditText)findViewById(R.id.editText);
        //chatText.setOnKeyListener(this);
    
        me = true;
        send = (Button)findViewById(R.id.button);
        change = (Button)findViewById(R.id.button2);
    
    
    
        list.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
    
        adp =  new TheAdapter(getApplicationContext(),R.layout.chat);
    
        list.setAdapter(adp);
    
        chatText.addTextChangedListener(textWatcher);
        checkFieldsForEmptyValues();
    
    
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                envoyer();
            }
    
        });
    
        change.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                me = !me;
                if (!me) {
                    change.setText(R.string.sender2);
                } else {
                    change.setText(R.string.sender);
                }
            }
        });
    }
    
    
    
    
    
    public void envoyer(){
    
        adp.add(new messages(me, chatText.getText().toString()));
        chatText.setText("");
    }
    
    private  void checkFieldsForEmptyValues(){
    
        String s1 = chatText.getText().toString();
    
        if (s1.length() < 0 ) {
            send.setEnabled(false);
        } else {
            send.setEnabled(true);
            send.setBackgroundColor(Color.BLUE);
            //send.setBackgroundColor((getResources().getColor(R.color.blue)));
        }
    
    }
    

Solution

  • In the onTextChanged is where you would check to see if the text field is empty:

    chatText.addTextChangedListener(new TextWatcher() {
    @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) { //enable}
                else if (s.length() == 0 { //disable }
    

    In your code, you have if (s1.length() < 0 ) which I don't think will ever be true because the text size will never be less than 0.