我有一个名为MeasurementList的 ListFragment ,它显示所有注册的测量数据。要注册新的测量数据,我使用名为NewMeasurement的 DialogFragment 和 AlertDialog 中的自定义视图,并填写所需的 UI 控件。
现在,我需要一个优雅的解决方案,在 DialogFragment 被解除后,用新注册的度量值更新 ListFragment 中的度量值列表。我不想从数据库中更新列表,而只是将新创建的测量对象添加到列表中。我尝试遵循 Android 指南,了解如何使片段通过回调接口与活动通信(为活动创建事件回调)。MeasurementList 将其引用传递给 NewMeasurement,因此它可以在注册新测量后回调它。问题是如何在 NewMeasurement.newInstance() 方法的 Bundle 中保存监听器引用。它主要保存原始数据类型,而不是像我这样的对象。
任何提示和建议将不胜感激。
测量列表.java
public class MeasurementList extends ListFragment implements OnMeasurementSetListener {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addMeasurement:
NewMeasurement newMeasurementDialog = NewMeasurement.newInstance(this);
newMeasurementDialog.show(getFragmentManager(), "newMeasurementDialog");
break;
default:
break;
}
return true;
}
@Override
public void onMeasurementSet(Measurement measurement) {
MeasurementAdapter listAdapter = (MeasurementAdapter) getListAdapter();
listAdapter.add(measurement);
}
}
OnMeasurementSetListener.java
public interface OnMeasurementSetListener {
public abstract void onMeasurementSet(Measurement measurement);
}
新测量.java
public class NewMeasurement extends DialogFragment
{
private OnMeasurementSetListener mListener;
public static NewMeasurement newInstance(OnMeasurementSetListener listener)
{
NewMeasurement nm = new NewMeasurement();
Bundle b = new Bundle();
b.putSerializable("listener", listener); // NOT WORKING
f.setArguments(b);
return f;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View v = factory.inflate(R.layout.layout_dialog_new_measurement, null);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.title_alert_dialog_new_weight);
builder.setIconAttribute(R.drawable.add);
builder.setView(v);
builder.setPositiveButton(R.string.alert_dialog_ok, this);
builder.setNegativeButton(R.string.alert_dialog_cancel, this);
return builder.create();
if (savedInstanceState != null)
mListener = (OnMeasurementSetListener) savedInstanceState.getSerializable("listener");
}
}