使用DialogFragment的结果通过Gridview OnItemClickListener更新数据库

时间:2015-07-25 06:07:50

标签: java android database gridview dialogfragment

我有一些Gridview,它是从数据库中提取的。 Gridview中填充了Textviews(显示时间),它们标记有必要的信息(ROW ID等),以便在数据库中对该时间进行更改。我为Gridview设置了OnItemClickListener,它将通过DialogFragment加载TimePickerDialog。

        // When items on the grid are pressed:
    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {
            String type = (String) (v.getTag(R.id.VIEW_TAG_TIMEENTRY_TYPE));
            String direction = (String) (v.getTag(R.id.VIEW_TAG_TIMEENTRY_DIRECTION));
            long row_id = (long) v.getTag(R.id.VIEW_TAG_TIMEENTRY_ID);

            // If entry doesn't exist
            if (row_id < 0) {
                DialogFragment dialogFragment = new TimePickerFragment();

                // Tell the dialogFragment what to do when set......

                dialogFragment.show(getSupportFragmentManager(), "timePicker");


            }
        }
    });

TimePickerFragment类如下:

public class TimePickerFragment extends DialogFragment
    implements TimePickerDialog.OnTimeSetListener {


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current time as the default values for the picker
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create a new instance of TimePickerDialog and return it
    return new TimePickerDialog(getActivity(), this, hour, minute,
            DateFormat.is24HourFormat(getActivity()));
}

public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    // Do something with the time chosen by the user

}

在我看过的大多数例子中,他们只是在onTimeSet函数中做了一些简单的事情,比如更新特定的textview。但是,我希望所采取的操作是添加或更新对应于单击的textview的行。

在C ++中,我可能已经传递了一个函数,它调用ContentProvider中的update方法作为该类构造函数的参数,但我不知道Java的等效设计模式。

有一个答案提到“接口”可能是要走的路,但我不知道如何实现这一点。 (Results from a DialogFragment to an ActivityFragment

使用setTargetFragment方法提到的另一个答案,但在这种情况下调用类是一个活动,所以我不能这样做。 (Receive result from DialogFragment

我应该如何最好地解决这个设计要求?我一直在骚扰我的android-app新手大脑。

非常感谢

1 个答案:

答案 0 :(得分:0)

你可以试试这个......

1。在你的TimePickerFragment ..

声明这个

public TimeListener listener;

public static abstract class TimeListener {
    public abstract void onTime(); // add parameters if you like
}
on on on on on [[[

public void onTimeSet(TimePicker视图,int hourOfDay,int minute){

    if(listener!=null)
         listener.onTime();

}

  1. 实例化您的对话框片段

    TimePickerFragment tm = new TimePickerFragment();

    tm.listener = new TimePickerFragment.TimeListener(){

     @Override
     public void onTime(){
    
         //do something here
    
     }
    

    }