应用程序正常打开,但是在打开此活动时显示“应用程序停止”。我不明白是什么问题。也许API级别与calendar.get()不兼容?如果可以,我该如何解决?
public class SearchRide extends AppCompatActivity { int p=1; private int year,month,day; Calendar calendar=Calendar.getInstance(); final EditText etDate=(EditText) findViewById(R.id.etDate); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search_ride); TextView tFrom=(TextView) findViewById(R.id.tFrom); TextView tTo=(TextView) findViewById(R.id.tTo); EditText etFrom=(EditText) findViewById(R.id.etFrom); EditText etTo=(EditText) findViewById(R.id.etTo); Button bSearch=(Button) findViewById(R.id.bSearch); ImageView iplussign=(ImageView) findViewById(R.id.iplussign); ImageView iminussign=(ImageView) findViewById(R.id.iminussign); final TextView tNumber=(TextView) findViewById(R.id.tNumber); tNumber.setText(String.valueOf(p)); iplussign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(p<=9) { p++; tNumber.setText(String.valueOf(p)); } } }); iminussign.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(p>=2) { p--; tNumber.setText(String.valueOf(p)); } } }); etFrom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ListFrom=new Intent(SearchRide.this,ListFrom.class); SearchRide.this.startActivity(ListFrom); } }); etTo.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent ToList =new Intent(SearchRide.this,ListTo.class); SearchRide.this.startActivity(ToList); } }); etDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new DatePickerDialog(SearchRide.this,listener,calendar.get(Calendar.DAY_OF_MONTH),calendar.get(Calendar.MONTH),calendar.get(Calendar.YEAR)).show(); } }); } DatePickerDialog.OnDateSetListener listener= new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { etDate.setText("4"); } };
}
您不能在OnCreate方法之外设置此代码。由于尚未创建布局,因此无法找到ViewById,因为它们的活动尚无内容。setContentView在执行任何有关视图的操作之前,您必须将其添加到活动中。
setContentView
final EditText etDate=(EditText) findViewById(R.id.etDate);
设置这些对象而不初始化它们,然后在完成后在onCreate中初始化 setContentView(LAYOUT);
setContentView(LAYOUT);
EditText etDate; public void onCreate(Bundle savedIntanceState) { .... etDate = findViewById(R.id.etDate);