在制作注冊界面時發現一個奇怪的問題public class MainActivity extends AppCompatActivity {
EditText a =(EditText) findViewById(R.id.xingming);
EditText b =(EditText) findViewById(R.id.mima);
Button zhuce = (Button) findViewById(R.id.zhuce);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(EditText) findViewById(R.id.xingming);
b =(EditText) findViewById(R.id.mima);
zhuce = (Button) findViewById(R.id.zhuce);
zhuce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(input()) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, nnn.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(MainActivity.this, "請輸入", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean input(){
String d=a.getText().toString();
String x=b.getText().toString();
if(d.equals("")||x.equals(""))
return false;
else
return true;
}
}
這麼寫的程序一打開就會停止運行
但是把findViewById放到onCreate方法中就沒有問題了
public class MainActivity extends AppCompatActivity {
EditText a;
EditText b;
Button zhuce;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
a=(EditText) findViewById(R.id.xingming);
b =(EditText) findViewById(R.id.mima);
zhuce = (Button) findViewById(R.id.zhuce);
zhuce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(input()) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, nnn.class);
startActivity(intent);
finish();
}
else {
Toast.makeText(MainActivity.this, "請輸入", Toast.LENGTH_SHORT).show();
}
}
});
}
private boolean input(){
String d=a.getText().toString();
String x=b.getText().toString();
if(d.equals("")||x.equals(""))
return false;
else
return true;
}
}
所以我想問一下findViewById使用時有什麼限制麼?
要在setContentView之後,再找元素。你想想,布局文件還沒加載,你要它去哪裡找元素呢?