android studio 非常新,這是我構建的第一個應用程式,因此我們將不勝感激。我設定了一個日歷,我正在嘗試將所選日期保存到共享首選項中。我的問題是我創建的方法沒有在我的 xml 檔案中顯示為 onclick 選項。
這是我到目前為止的代碼:
public class calendar extends AppCompatActivity {
CalendarView calendarView;
SharedPreferences booking_date;
String myDate, txt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calendar);
calendarView = findViewById(R.id.id_calendarView);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull CalendarView view, int year, int month, int dayOfMonth) {
myDate = dayOfMonth " " (month 1) " " year; // note the months start at 0
//redDateText.setText(myDate);
}
});
}
public void goSaveDate(View view){
booking_date = getApplicationContext().getSharedPreferences("booking_details", MODE_PRIVATE);
txt = myDate;
SharedPreferences.Editor editor = booking_date.edit();
editor.putString("key_date", txt);
editor.commit();
Toast.makeText(getBaseContext(), "Date Saved!!", Toast.LENGTH_SHORT).show();
}
public void goShowDate(View view){
booking_date = getApplicationContext().getSharedPreferences("booking_details", MODE_PRIVATE);
String name = booking_date.getString("key_date", null);
TextView textView = findViewById(R.id.textView5);
textView.setText("Your Next booking is on: " name);
}
@Override
public void finish () {
super.finish();
overridePendingTransition(R.transition.slide_in_left, R.transition.slide_out_right);
}
}
uj5u.com熱心網友回復:
除非您使用視圖資料系結,否則android:onClick="goSaveDate"在 XML 布局中設定on Views的(舊)方法已被棄用。
Deprecated:View 實際上是遍歷 Context 層次結構尋找相關方法,這種方法很脆弱,限制了 R8 等位元組碼優化器。相反,使用 View.setOnClickListener。
您可以從活動類內部設定 OnClickListener,例如在 onCreate 方法內部。
// each click on R.id.button_save_date will call the goSaveDate method
findViewById(R.id.button_save_date).setOnClickListener(this::goSaveDate);
findViewById(R.id.button_show_date).setOnClickListener(this::goShowDate);
將R.id.button_save_date和替換R.id.button_show_date為您希望在其上設定點擊偵聽器的視圖的 id。如果這些視圖(XML 中的按鈕、組件)仍然沒有android:id="@ id/..."在 XML 布局中設定屬性,則首先添加該屬性。
語法::( this::goSaveDate) 是一個方法參考。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372332.html
