将数据从片段传递到DialogFragment的最佳方法

时间:2013-07-10 20:45:34

标签: android

我正在尝试找出在Fragment和DialogFragment之间传递数据的最佳方法。 (双向沟通)

首先我有一个Dialog Fragment,允许用户选择用于旅行的司机/车辆。用户可以选择多个驾驶员和车辆。这是DialogFragment类的片段:

public class DriverVehiclePickersDialogFragment extends DialogFragment implements OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {

    private static final int DRIVERS_LOADER = 0;
    private static final int VEHICLES_LOADER = 1;

    // Parent view for all rows and the add button.
    private LinearLayout mContainerView;

    // These are the Contacts rows that we will retrieve.
    static final String[] DRIVERS_SUMMARY_PROJECTION = new String[] { BaseColumns._ID, ConsoleContract.Drivers.DRIVER_NUMBER, ConsoleContract.Drivers.DRIVER_NAME };
    static final String[] VEHICLES_SUMMARY_PROJECTION = new String[] { BaseColumns._ID, ConsoleContract.Vehicles.VEHICLE_NUMBER, ConsoleContract.Vehicles.VEHICLE_VIN };

    public interface DriverVehicleDialogListener {
        public void onDialogPositiveClick(????????);
    }

    @Override
    public void onClick(View v) {
        if (v.equals(mSet)) {
            if (checkDriversVehiclesValidity()) {
                mListener.onDialogPositiveClick(???????????);
                this.dismiss();
            }
        } else if (v.equals(mCancel)) {
            this.dismiss();
        } else if (v.equals(mAddNew)) {
            inflateEditRow();
        } else if (v instanceof ImageButton) {
            mContainerView.removeView((View) v.getParent());
        }
    }

    // Helper for inflating a row
    private void inflateEditRow() {

        Bundle args = getArguments();
        DialogType dialogType = (DialogType) args.getSerializable(ARG_DIALOG_TYPE);
        final View rowView = getActivity().getLayoutInflater().inflate(R.layout.driver_vehicle_row, null);
        CustomAutoCompleteTextView driversField, vehiclesField;

        if ((dialogType == DialogType.DRIVER_SPINNER) || (dialogType == DialogType.DRIVER_VEHICLE_SPINNER)) {
            driversField = (CustomAutoCompleteTextView) rowView.findViewById(R.id.drivers_field);
            driversField.setThreshold(0);
            driversField.setAdapter(mDriversAdapter);
            driversField.setVisibility(View.VISIBLE);
        }

        if ((dialogType == DialogType.VEHICLE_SPINNER) || (dialogType == DialogType.DRIVER_VEHICLE_SPINNER)) {
            vehiclesField = (CustomAutoCompleteTextView) rowView.findViewById(R.id.vehicles_field);
            vehiclesField.setThreshold(0);
            vehiclesField.setAdapter(mVehiclesAdapter);
            vehiclesField.setVisibility(View.VISIBLE);
        }

        ImageButton mDelete = (ImageButton) rowView.findViewById(R.id.buttonDelete);
        mDelete.setOnClickListener(this);

        // Inflate at the end of all rows but before the "Add new" button
        mContainerView.addView(rowView, mContainerView.getChildCount() - 1);
    }
}

这是我的车辆类:

public static final class Vehicles implements VehicleColumns, BaseColumns {

    public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_VEHICLES).build();
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/com.test.console.vehicles";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.console.vehicles";

    private int vehicle_id, vehicle_number;
    private String vehicle_vin;

    public Vehicles() { 
    }

    public Vehicles(int vehicleID, int vehicleNumber, String vehicleVin) {
        setVehicleID(vehicleID);
        setVehicleNumber(vehicleNumber);
        setVehicleVin(vehicleVin);
    }

    public int getVehicleID() {
        return vehicle_id;
    }

    public void setVehicleID(int mVehicleID) {
        this.vehicle_id = mVehicleID;
    }

    public int getVehicleNumber() {
        return vehicle_number;
    }

    public void setVehicleNumber(int mVehicleNumber) {
        this.vehicle_number = mVehicleNumber;
    }

    public String getVehicleVin() {
        return vehicle_vin;
    }

    public void setVehicleVin(String mVehicleVin) {
        this.vehicle_vin = mVehicleVin;
    }

    public static Uri buildVehicleUri(String vehicleID) {
        return CONTENT_URI.buildUpon().appendPath(vehicleID).build();
    }
}

这是我的驱动程序类:

public static final class Drivers implements DriverColumns, BaseColumns {

    public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_DRIVERS).build();
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/com.test.console.drivers";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.console.drivers";

    private int driver_id, driver_number;
    private String driver_name;

    public Drivers() {  
    }

    public Drivers(int driverID, int driverNumber, String driverName) {
        this.setDriverID(driverID);
        this.setDriverNumber(driverNumber);
        this.setDriverName(driverName);
    }

    public static Uri buildDriverUri(String driverID) {
        return CONTENT_URI.buildUpon().appendPath(driverID).build();
    }

    public int getDriverID() {
        return driver_id;
    }

    public void setDriverID(int driver_id) {
        this.driver_id = driver_id;
    }

    public int getDriverNumber() {
        return driver_number;
    }

    public void setDriverNumber(int driver_number) {
        this.driver_number = driver_number;
    }

    public String getDriverName() {
        return driver_name;
    }

    public void setDriverName(String driver_name) {
        this.driver_name = driver_name;
    }
}

这是我的片段调用dialogfragment来选择驱动程序/车辆:

public class CrewTripFragment extends Fragment implements DateTimeDialogListener, CrewCountDialogListener, DriverVehicleDialogListener, OnItemSelectedListener {

    @Override
    public void onDialogPositiveClick(????) {
        //I need a list of drivers+vehicles selected so i can use it in the fragment.
        //an example would be: 
        //DriverID: 10 DriverName: John DriverNumber 30 - VehicleID 10 VehicleNumber: 24 VehicleVin: 34848
    }

    protected void showDriverVehicleDialog() {

        // Creating a bundle object
        Bundle bundleSettings = new Bundle();
        bundleSettings.putInt(DriverVehiclePickersDialogFragment.ARG_TITLE_RESOURCE, R.string.crew_driver_vehicle_title);
        bundleSettings.putSerializable(DriverVehiclePickersDialogFragment.ARG_DIALOG_TYPE, DriverVehiclePickersDialogFragment.DialogType.DRIVER_VEHICLE_SPINNER);

        if (mDrivers != null) {
            bundleSettings.putLongArray(DriverVehiclePickersDialogFragment.ARG_SET_DRIVER, mDrivers);
        }

        if (mVehicles !=  null) {
            bundleSettings.putLongArray(DriverVehiclePickersDialogFragment.ARG_SET_VEHICLE, mVehicles);
        }

        DriverVehiclePickersDialogFragment dialogDriverVehiclePicker = DriverVehiclePickersDialogFragment.newInstance(this, bundleSettings);
        dialogDriverVehiclePicker.show(getFragmentManager(), getTag());
    }

我在想是否应该将对话片段中的驱动程序列表和车辆列表传递回片段?

我还在考虑将一个URI数组传回Fragment,但这不是一个好主意,因为数据库与webservice保持同步,如果它同步并且sqlite数据库中的记录被删除,那么我无法检索片段内的数据。

我真的不确定什么是最好的解决方案,任何帮助都会受到高度赞赏。

2 个答案:

答案 0 :(得分:3)

您可以选择任何您想要的方法。

请注意,在某些情况下,片段/活动可能会重新创建(例如旋转设备时),所以你也需要处理它(除非你没关系,对话框将会消失。

因为你正在使用setArguments和getArguments,所以你可以使用onSaveInstanceState,但同样,这一切都取决于你想对这些情况做什么。

要传递给活动的数据,您甚至可以使用自己的监听器。

答案 1 :(得分:1)

无需在代码中查看详细信息,以下是我的工作方式(通过Activity将数据从Fragment传递到DialogFragment):

像往常一样在Frag1中声明一个在Act:

中实现的静态接口
public static interface DataProxy {
   void sendData(Object ... args);
}

准备DFrag以通过某种方法接收数据:

public void recvData(Object ... data){ ... }

假设DFrag is shown using a tag

DialogFragment newFragment = MyDialogFragment.newInstance(mStackLevel);
newFragment.show(getSupportFragmentManager().beginTransaction(), "my-dialog");

然后从法案:

@Override
public void sendData(Object ...data) {
    Fragment frag = getSupportFragmentManager().findFragmentByTag("my-dialog");
    if(frag != null && frag instanceof MyDialogFragment) {
        ((MyDialogFragment) frag).recvData(data);
    }
}