无法从方法中引用类按钮

时间:2016-02-20 17:09:47

标签: java android

我在Main Activity中声明了一个按钮,但在运行应用程序时获取NullObjectReference。无论我在哪里尝试移动声明(在类之外,在onCreate方法中等),它都会声明声明或按钮引用。我看到推荐状态与非静态类/方法的帖子,但我是OOP的新手,并不确定如何实现它。谁能告诉我我做错了什么?

public class MainActivity extends AppCompatActivity {
    …
    // Declare button in the MainActivity 
    Button btnWrong = (Button)findViewById(R.id.btnWrong);
    ...

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // WHEN USER TAPS ITEMS ON APPBAR
    switch (item.getItemId())  {
        case R.id.mnuLoad:  // If use taps "Load"
            final Dialog dialog = new Dialog(MainActivity.this); /
    …

btnLoad.setOnClickListener(new View.OnClickListener()  {
    @Override
    public void onClick(View v) {
        deckNumber = deckPicker.getValue();
        if …        }
        dialog.dismiss();
        btnWrong.setEnabled(true); // Trying to reference the button here

2 个答案:

答案 0 :(得分:0)

你必须这样做:

Button btnWrong; //Declare button as private 之外(在公共类MainActivity下扩展AppCompatActivity)

onCreate()
btnWrong = (Button)findViewById(R.id.btnWrong);

中的

btnWrong

现在,您可以在其班级的任何位置使用scanForPeripheralsWithServices

答案 1 :(得分:0)

试试这个:

public class MainActivity extends AppCompatActivity {

    // Declare as class field
    Button btnWrong;

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

        btnWrong = (Button)findViewById(R.id.btnWrong);
    }
    ....
}