我剛剛編寫了一個Android程序,它包含在DatePicker中,但它不起作用。無法在Android中創建DatePicker
Java代碼:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
CurDateTv2 = (TextView)findViewById(R.id.textView2);
Picker = (DatePicker)findViewById(R.id.calendarView1);
btnChangeDate = (Button)findViewById(R.id.button1);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
Picker.init(year, month,day, onChangedListener())
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
public void onDateChangedListener(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
CurDateTv2.setText(new String Builder()
.append(dayOfMonth).append("/").append(monthOfYear + 1)
.aapend("/").append(year).append(" "));
}
}
而且佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Current Date"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="08/08/2016"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<CalendarView
android:id="@+id/calendarView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
不幸的是,我不知道Java的非常好,所以我不能識別錯誤所在。
我真的希望你能幫助我。
如果你有聲明這個「選擇器」變量和資源的第二每個初始化只應後的setContentView()方法,你必須首先初始化資源,然後調用的setContentView ()所以改變它 – Vickyexpert
聲明你的選擇器即Picker =(DatePicker)findViewById(R.id.calendarView1); 和其他變量低於 super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); –