【问题标题】:How can i make my button become visible with TextChanger?如何使用 TextChanger 使我的按钮变得可见?
【发布时间】:2017-09-05 06:36:24
【问题描述】:

我在 xml 中制作了一个不可见的按钮,当我的 EditText 中的某个字符串值被制作时,我想让按钮再次可见。当使用 if 语句满足值时,我使用了 TextWatcher 检查。但是,当执行显示按钮的代码时,应用程序崩溃说 textwatcher 停止工作。我对android开发很陌生,所以可能是我搞砸了。

这是我的代码:

public class MainActivity extends AppCompatActivity
{
    private EditText UserInput;
    private Button button;

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

        Button button = (Button)findViewById(R.id.button);
        UserInput = (EditText) findViewById(R.id.UserInput);
        UserInput.addTextChangedListener(watch);
    }

    TextWatcher watch = 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) {

            if(s.toString().equals("teststring") ){
                //program crashes when it reaches this part
                button.setVisibility(View.VISIBLE);
            }
            else 
            {

            }
        }
        @Override
        public void afterTextChanged(Editable s) {

        }
    };      
}

【问题讨论】:

  • 发布你的日志

标签: android button visibility android-textwatcher


【解决方案1】:

改变这一行

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

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

这样类成员按钮就被初始化了

【讨论】:

    【解决方案2】:

    您已经在此处将 Button 定义为 全局 变量:

    private Button button;
    

    但是当您在 onCreate 方法中定义视图时,您定义了一个 Local 变量 Button 并在此处实例化它:

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

    稍后当您在Button 上调用setVisibility 时,您会在未实例化的全局 变量上调用此方法。 要解决这个问题,只需像这样更改您的 onCreate 方法:

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

    所以 全局 变量被实例化了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 2020-11-21
      • 2018-02-08
      • 2011-05-09
      • 2011-06-04
      相关资源
      最近更新 更多