8

我是 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;
}
}
4

2 回答 2

14

编辑:

EditText ShowDate = (EditText)getActivity(). findViewById(R.id.editTextToShowDate);  

这将工作...

于 2013-02-25T17:21:54.870 回答
0
于 2017-10-24T19:25:44.763 回答