2013-02-07 99 views
2

我創建了一個片段與此指導時間選擇:安卓:發送時間選取的片段數據到活動

http://developer.android.com/guide/topics/ui/controls/pickers.html

現在我要在設定的時間發回活動舉行片段。我搜索如何做到這一點,我發現這一點:

http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity

我想在我的片段創建onTimeSet的接口,但由於我採取TimePickerDialog.OnTimeSetListener它要求我重寫onTimeSet方法。我發現我可以簡單地調用getActivity()方法發送數據,但我不確定這是否是一個很好的選擇,因爲android開發頁面使用接口方法推薦。

我該怎麼辦?

下面是一些代碼:

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())); 
} 

@Override 
public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
    // WHAT TO DO?? 
} 


} 

在我的活動:

.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      DialogFragment newFragment = new TimePickerFragment(); 
      newFragment.show(CreateStopActivity.this.getSupportFragmentManager(), "timePicker"); 
     } 

    }); 

回答

0

我想你應該實現在您的活動TimePickerDialog.OnTimeSetListener接口。您在哪裏創建TimePickerFragment。如下所示:

public class YourActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener { 
    @Override 
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
     // DO HERE ANYTHING WITH DATA 
    } 
} 

並且不要忘記在構造函數中傳遞OnTimeSetListener的activity。

dialog = new TimePickerDialog(yourContext, yourActivity, hourOfDay, minute, is24HourView); 

手錶TimePickerDialog瞭解更多信息

+0

dialog.setOnTimeSetListener()?此方法不存在。 – Pablo

+0

@Pablo你是對的。對話框的TimeSetListener應該通過構造函數傳輸。 – grine4ka

1

你可以用構造函數傳遞。

Button timeBtn; 

    public TimePickerFragment(Button btn) { 
     timeBtn = btn; 
    } 

    public void onTimeSet(TimePicker view, int hourOfDay, int minute) { 
     timeBtn.setText(hourOfDay + ":" + minute); 
    }