私はJavaを初めて使用し、EditTextを使用してアクティビティを作成しようとしています。作成時に現在の日付が読み込まれ、ユーザーがEditTextを選択すると、DatePickerが表示されます。ユーザーが日付を選択したら、結果をEditTextに入れる必要があります。ただし、現在、次のエラーが発生しています。
タイプActivityから非静的メソッドfindViewById(int)への静的参照を作成できません
非静的メソッドへの静的参照を作成できないことを知っています。すべての静的参照を削除しようとしましたが、これにより他のエラーが発生しました。私のコードは以下の通りです。
これを機能させる方法のサンプルコードを手伝ってもらえますか?エラーは、結果をEditTextに入れようとしたときに発生します。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get Current Date and assign to EditText Begin
Calendar c = Calendar.getInstance();
System.out.println("Current time => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
String formattedDate = df.format(c.getTime());
EditText ShowDate = (EditText) findViewById(R.id.editTextToShowDate);
ShowDate.setText(formattedDate);
//Get Current Date and assign to EditText End
}
//Date Picker Start
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB) public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@TargetApi(Build.VERSION_CODES.HONEYCOMB) @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
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);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
String sToDate = createStringFromDateElements(year, month, day);
EditText ShowDate = (EditText) findViewById(R.id.editTextToShowDate); //I get the error here
ShowDate.setText(sToDate);
}
private String createStringFromDateElements(int year, int month, int day) {
// TODO Auto-generated method stub
return null;
}
}
//Date Picker End
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}