我有两节课。一个是我的主要活动,另一个是帮助方法,它应该打开一个Android DatePicker。到目前为止一切正常,除非我想从日期选择器类中检索日期。这是我的课程:
// This is the class that creates the date picker
package com.strom.myapp;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
import java.util.Calendar;
public class DefaultDatePicker extends DialogFragment implements DatePickerDialog.OnDateSetListener {
private String returnDate;
public String getReturnDate() {
return returnDate;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
returnDate = String.valueOf(dayOfMonth) +
"." +
String.valueOf(monthOfYear) +
"." +
String.valueOf(year) +
", 00:00";
}
}
这是主要的活动
package com.strom.myapp;
import android.app.DialogFragment;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class BalanceScreen extends ActionBarActivity {
private String payDate;
// ... omitted code ...
@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
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_payDate) {
DialogFragment datePicker = new DefaultDatePicker();
datePicker.show(getFragmentManager(), "datePicker");
payDate = datePicker.getReturnDate();
return true;
}
// ... omitted code ...
}
getter-method' datePicker.getReturnDate();'无法从主活动访问,即使它们位于同一个包中。我不明白为什么这不应该奏效。我在这里错过了什么?
答案 0 :(得分:5)
我建议你替换:
DialogFragment datePicker = new DefaultDatePicker();
与
DefaultDatePicker datePicker = new DefaultDatePicker();
因为你的方法getReturnDate是在DefaultDatePicker中声明的,而不是在DialogFragment中声明。
答案 1 :(得分:0)
您可以将datePicker
(提交 DefaultDatePicker 的实例)转发给DefaultDatePicker
,以调用特定于DatePickerDialog.OnDateSetListener
的方法。
((DefaultDatePicker)datePicker).getReturnDate()
答案 2 :(得分:0)
向您的活动添加公共变量
public String dateFromPicker = "";
在DefaultDatePicker
方法onDateSet
执行此操作
((BalanceScreen)getActivity()).dateFromPicker = returnDate;