我在android中开发了一个简单的DatePicker(通过android devolper)应用程序进行测试。我用过Fragment Dialog。 一切正常,选择日期然后点击确定后,对被覆盖的 onDateSet(DatePicker视图,int year,int month,int day)进行回调
到目前为止一切顺利。但是这是一个外部MainActivity类的静态内部类,我现在不能弄明白我怎样才能回调mainAcitity?我在MainActivity中有三个字段(年,月) ,一天)我想在点击" ok"之后设置。在FragmentDialog中。我现在只能访问内部静态类中的字段。
这可能听起来很愚蠢 - 但是我怎么能以一种很好的方式通知MainActivity" ok"在片段中点击,然后立即收到YEAR,MONTH和DAY。
感谢!!!
public class MainActivity extends FragmentActivity {
private int year, month, day;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
@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(), DatePickerFragment.this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
System.out.println("year = " + year + "\n month = " + month + "\nday = " + day);
}
}
XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="test"
android:onClick="showTimePickerDialog" />
</RelativeLayout>
答案 0 :(得分:3)
不需要回调,你需要做的是覆盖positive button
或OK button
并从活动中调用一个方法来通知按下按钮,然后你就可以了。立即收到YEAR,MONTH和DAY。&#34;从你的活动方法
<强>样品:强>
@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);
DatePickerDialog date = new DatePickerDialog(getActivity(), DatePickerFragment.this, year, month, day);
date.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
notifyActivity(); //must be the method from the activity
}
});
return date;
}
答案 1 :(得分:0)
由于您拥有getActitity()方法,因此您可以将活动强制转换为类,例如MainActivity,并调用您喜欢的公共方法:
.setPositiveButton(“Jugar de Nuevo”,新的 DialogInterface.OnClickListener(){ public void onClick(DialogInterface对话框,int id){ MainActivity活动=(MainActivity)getActivity(); activity.initGame(); } })