質問

I have a Fragment that has its own layout and has a Choose Time button along with a TextView beneath it. I am opening a TimePickerFragment from this Fragment when the user clicks this button. Now when the user selects a time, and clicks done, I want to populate the TextView contained in the fragment. I am not sure how to do this.

All the materials/tutorials online invoke the timepicker from an Activity. I do (obviously) have a Parent Activity, but since this TimePicker is only being used in this Fragment, I would like to limit the scope as much as possible.
So the flow is as follows:
ParentActivity > Fragment (contains TextView and button) > DialogFragment (TimePicker)

Here is my implementation:

public class TimePickerFragment extends DialogFragment  implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        int hour = 0; 
        int minute = 0;
        boolean is24Hour = false; 

        // ... Some code to read shared preference, get the correct time format, theme, etc.

        return new TimePickerDialog(getActivity(), dialog_theme, this, hour, minute, is24Hour); //DateFormat.is24HourFormat(getActivity())

    }

    @Override
    public void onTimeSet(TimePicker view, int hour, int minute) {

        //TextView textView = (TextView) getView.findViewById(R.id.time_value); //NullPointerException! 
        TextView textView = (TextView) view.findViewById(R.id.time_value); //Also NullPointerException! 

        // Do something with the time chosen by the user
        textView.setText(TimeAndDate.getDisplayableTime(time));

        textView.clearFocus();

    }

}
役に立ちましたか?

解決

It belongs to the Fragment which invokes the DialogFragment

findViewById looks for a view with the id in the current view hierarchy. The TextView is not a child of TimerView.

So you need to initialize TextView in Fragment not DialogFragment.

All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly. Use interface as a call back to the Activity and then communciate the time to the Fragment.

http://developer.android.com/training/basics/fragments/communicating.html

DialogFragment --> ParentActivtiy --> Fragment

You can check the example @

Simple timepicker for a fragment activity

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top