1

我在 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) {

        }
    };      
}
4

2 回答 2

1

您已经在这里定义了您Button全局变量:

private Button button;

但是当你在onCreate方法中定义视图时,你定义了一个局部变量Button并实例化它,在这里:

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

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

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

所以全局变量被实例化。

于 2017-04-10T09:31:11.920 回答
0

更改此行

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

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

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

于 2017-04-10T09:25:36.717 回答