0

我有 2 种方法,它们使用相同的 2 个按钮 + 1 个 TextView。像这样的东西:

public void startChange(View v) {
    final Button start = (Button) findViewById(R.id.start);
    final Button restart = (Button) findViewById(R.id.restart);
    final TextView check = (TextView) findViewById(R.id.check);
    //TO-DO part - Sets check to something based on buttons TagID
}

public void restartChange (View v) {
    final Button start = (Button) findViewById(R.id.start);
    final Button restart = (Button) findViewById(R.id.restart);
    final TextView check = (TextView) findViewById(R.id.check);
    //TO-DO part - Restars everything to basic position
}

一切正常.. 但是一旦我制作了这个按钮和 textview 全局变量,我就得到了 java.lang.NullPointerException。知道如何解决吗?

编辑: 问题解决了。只认为您要做的就是在 onCreate 方法中定义按钮和文本视图,而不是在全局定义中。

例子:

public class Example extends Activity {
    Button start;
    Button restart;
    TextView t;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start = (Button) findViewById(R.id.start);
        restart = (Button) findViewById(R.id.restart);
       check = (TextView) findViewById(R.id.check);
    }
}
4

2 回答 2

0

问题解决了。只认为您要做的就是在 onCreate 方法中定义按钮和文本视图,而不是在全局定义中。

例子:

public class Example extends Activity {
    Button start;
    Button restart;
    TextView t;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        start = (Button) findViewById(R.id.start);
        restart = (Button) findViewById(R.id.restart);
       check = (TextView) findViewById(R.id.check);
    }
}
于 2014-03-25T09:25:55.003 回答
0

您必须添加setContentView(R.layout.main);

public class Example extends Activity
{
    Button start;
    Button restart;
    TextView t;

    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        start = (Button) findViewById(R.id.start);
        restart = (Button) findViewById(R.id.restart);
        check = (TextView) findViewById(R.id.check);
    }
}
于 2012-11-04T23:59:19.550 回答