如何使用TextChanger使我的按钮变得可见?

时间:2017-04-10 09:24:16

标签: android button visibility android-textwatcher

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

        }
    };      
}

2 个答案:

答案 0 :(得分:1)

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

private Button button;

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

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

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

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

因此全局变量得到实例化。

答案 1 :(得分:0)

更改此行

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

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

使类成员按钮初始化

相关问题