我是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;
}
}
答案 0 :(得分:14)
编辑:
EditText ShowDate = (EditText)getActivity(). findViewById(R.id.editTextToShowDate);
这会有用......
答案 1 :(得分:0)