2017-04-10 64 views
1

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

这里是我的代码:

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

     } 
    };  
} 
+0

发布您的logcat – Moulesh

回答

0

改变这一行

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

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

这样的类成员按钮得到初始化

1

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

private Button button; 

但是当你定义内onCreate方法的观点,你定义一个本地变量Button并创建实例,在这里:

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

后来,当你调用setVisibilityButton,您在Global变量上调用此方法时未实例化。 为了解决s刊简单的改变你的onCreate方法是这样的:

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

所以全球变量实例化。

相关问题