Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Showing a DialogFragment


231

Showing a DialogFragment


Like all fragments, instances of DialogFragment are managed by the FragmentManager of the hosting
activity.


To get a DialogFragment added to the FragmentManager and put onscreen, you can call the following
methods on the fragment instance:


public void show(FragmentManager manager, String tag)
public void show(FragmentTransaction transaction, String tag)


The string parameter uniquely identifies the DialogFragment in the FragmentManager’s list. Whether
you use the FragmentManager or FragmentTransaction version is up to you. If you pass in a
FragmentTransaction, you are responsible for creating and committing that transaction. If you pass in
a FragmentManager, a transaction will automatically be created and committed for you.


Here, you will pass in a FragmentManager.


In CrimeFragment, add a constant for the DatePickerFragment’s tag. Then, in onCreateView(...),
remove the code that disables the date button and set a View.OnClickListener that shows a
DatePickerFragment when the date button is pressed.


Listing 12.3  Showing your DialogFragment (CrimeFragment.java)


public class CrimeFragment extends Fragment {


private static final String ARG_CRIME_ID = "crime_id";
private static final String DIALOG_DATE = "DialogDate";
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setText(mCrime.getDate().toString());
mDateButton.setEnabled(false);
mDateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
DatePickerFragment dialog = new DatePickerFragment();
dialog.show(manager, DIALOG_DATE);
}
});


mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
...
return v;
}
}


http://www.ebook3000.com

Free download pdf