我有两种使用相同的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方法中定义按钮和textview,而不是在全局定义中。
示例:
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);
}
}
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
问题解决了。 只认为你要做的是在onCreate方法中定义按钮和textview,而不是在全局定义中。
示例:
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);
}
}