Last active
August 19, 2018 20:23
-
-
Save blehr/59866174a314e03e8a1697fc83880d1d to your computer and use it in GitHub Desktop.
Calling a DatePickerFragment from a fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyFragment extends Fragment { | |
EditText dateOfBirthET; | |
String selectedDate; | |
public static final int REQUEST_CODE = 11; // Used to identify the result | |
private OnFragmentInteractionListener mListener; | |
public MyFragment() { | |
// Required empty public constructor | |
} | |
public static MyFragment newInstance() { | |
MyFragment fragment = new MyFragment(); | |
return fragment; | |
} | |
@Override | |
public void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
} | |
@Override | |
public View onCreateView(LayoutInflater inflater, ViewGroup container, | |
Bundle savedInstanceState) { | |
// Inflate the layout for this fragment | |
View view = inflater.inflate(R.layout.fragment_my, container, false); | |
dateOfBirthET = view.findViewById(R.id.dateOfBirthET); | |
// get fragment manager so we can launch from fragment | |
final FragmentManager fm = ((AppCompatActivity)getActivity()).getSupportFragmentManager(); | |
// Using an onclick listener on the editText to show the datePicker | |
dateOfBirthET.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View v) { | |
// create the datePickerFragment | |
AppCompatDialogFragment newFragment = new DatePickerFragment(); | |
// set the targetFragment to receive the results, specifying the request code | |
newFragment.setTargetFragment(MyFragment.this, REQUEST_CODE); | |
// show the datePicker | |
newFragment.show(fm, "datePicker"); | |
} | |
}); | |
return view; | |
} | |
@Override | |
public void onActivityResult(int requestCode, int resultCode, Intent data) { | |
// check for the results | |
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) { | |
// get date from string | |
selectedDate = data.getStringExtra("selectedDate"); | |
// set the value of the editText | |
dateOfBirthET.setText(selectedDate); | |
} | |
} | |
@Override | |
public void onAttach(Context context) { | |
super.onAttach(context); | |
if (context instanceof OnFragmentInteractionListener) { | |
mListener = (OnFragmentInteractionListener) context; | |
} else { | |
throw new RuntimeException(context.toString() | |
+ " must implement OnFragmentInteractionListener"); | |
} | |
} | |
@Override | |
public void onDetach() { | |
super.onDetach(); | |
mListener = null; | |
} | |
public interface OnFragmentInteractionListener { | |
// TODO: Update argument type and name | |
void onFragmentInteraction(Uri uri); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment