当用户开始在安卓中输入时,如何使用发送按钮更改麦克风图标



Whatsapp当您开始键入消息时,麦克风图标将替换为发送图标。我们该怎么做呢?

只需在EditText上添加TextChangedListener:

EditText commentText=(EditText)findViewById(R.id.edit);
    commentText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            String val=charSequence.toString();
            // chaeck if edittext have any character or empty. then
            // there are two way to handle switch buttons
            //1. Take two button at same position and based on condition just change their visibility
            //2. Just take one button and based on condition just change src image and add Tag text to the button view.
            // Tag text will help to identify click listener action.
            ///****************** first way ******///////
            firstWay(val);
            ///****************** second way ******///////
            secondWay(val);
        }
        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

第1种方法...

    private void firstWay(String val) {
    if (val.isEmpty())
    {
        button1.setVisibility(View.GONE);
        button2.setVisibility(View.VISIBLE);
    }
    else
    {
        button1.setVisibility(View.VISIBLE);
        button2.setVisibility(View.GONE);
    }
}

第二种方法。

    private void secondWay(String val) {
    if (val.isEmpty())
    {
        button1.setImageResource(R.drawable.ic_mic_black_24dp);
        button1.setTag("mic");
    }
    else
    {
        button1.setImageResource(R.drawable.ic_send_black_24dp);
        button1.setTag("send");
    }
}

当您单击按钮时,只需检查标签值是否等于"麦克风"执行与麦克风相关的操作,否则其他操作。

button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String tagValue=button1.getTag().toString();
            if (tagValue.equals("mic"))
            {
                /// mic related operation 
            }
            else 
            {
                /// other operation 
            }
        }
    });

将 TextWatcher 设置为 EditText。像这样:

   editText.addTextChangedListener(new TextWatcher() {
   @Override
   public void afterTextChanged(Editable s) {}
   @Override    
   public void beforeTextChanged(CharSequence s, int start,
     int count, int after) {
   }
   @Override    
   public void onTextChanged(CharSequence s, int start,
     int before, int count) {
      if(s.length() != 0)
        fab.setImageDrawable(/*enter send icon here*/);
        else fab.setImageDrawable(/*enter mic icon here*/);
   }
  });