Android:仅当填写了编辑文本时,应用启动时禁用按钮才启用

问题描述

我要Android:仅在填充“编辑”文本时启用应用启动时禁用按钮。需要帮助。提前致谢。我是Android初学者。 尝试使用TextWatcher。当我不添加功能时,应用程序运行正常。 请建议我如何实现TextWatcher部分。该应用程序的其余部分运行正常。

代码如下:

package com.example.intentopennextscreen;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

  public TextView editText1;
  public Button submit;

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



      //editText1.addTextChangedListener(ebert);
    }


    

  /*TextWatcher ebert = new TextWatcher(){
    @Override
    public void beforeTextChanged(CharSequence s,int start,int count,int after) {

    }

    @Override
    public void onTextChanged(CharSequence s,int before,int count) {
      String message = editText1.getText().toString().trim();

      submit.setEnabled(!message.isEmpty());
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
  };  */




    /* Called when the user taps the Send button */
    public void sendMessage(View view) {

      /* Creating instance of Intent object */
      Intent intent = new Intent(this,displayMessageActivity.class);

      /* finding the user-input provided in the editText as an object  */
      EditText editText1 = (EditText) findViewById(R.id.editText1);

      /*Finding Button Element*/
      Button submit = (Button) findViewById(R.id.button);













      /* converting the user-input of editText as String  */
      String message = editText1.getText().toString().trim();







        /* sending the message to other activity as Key-Value Pair */
        intent.putExtra("Value",message);

        /* starting the intent */
        startActivity(intent);
    }
}

解决方法

您可以在afterTextChanged内移动按钮操作

@Override
public void afterTextChanged(Editable s) {
    submit.setEnabled(!s.isEmpty());
}
,

请尝试以下代码,
将此添加到您的TextFormField( maxLength: 10,buildCounter: (BuildContext context,{ int currentLength,int maxLength,bool isFocused }) => null,); 方法中

onCreate()