I\'m trying to create a DialogFragment
using a custom view in an AlertDialog
. This view must be inflated from xml. In my DialogFragment
As i needed long time for solving the same problem (Pop up a simple Text Dialog) i decided to share my solution:
The layoutfile connectivity_dialog.xml contains a simple TextView with the message text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:text="Connectivity was lost"
android:textSize="34sp"
android:gravity="center"
/>
</RelativeLayout>
The Activity showing the "dialog" implements a inner class (as DialogFragment is a Fragment and not a Dialog; further info see https://stackoverflow.com/a/5607560/6355541). The Activity can activate and deactivate the DialogFragment via two functions. If you're using android.support.v4, you may want to change to getSupportFragmentManager():
public static class ConnDialogFragment extends DialogFragment {
public static ConnDialogFragment newInstance() {
ConnDialogFragment cdf = new ConnDialogFragment();
cdf.setRetainInstance(true);
cdf.setCancelable(false);
return cdf;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.connectivity, container, false);
}
}
private void dismissConn() {
DialogFragment df = (DialogFragment) getFragmentManager().findFragmentByTag("conn");
if (df != null) df.dismiss();
}
private void showConn() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("conn");
if (prev != null) ft.remove(prev);
ft.addToBackStack(null);
ConnDialogFragment cdf = ConnDialogFragment.newInstance();
cdf.show(ft, "conn");
}
I haven't inflated from XML but I have done dynamic view generation in a DialogFragment successfully:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
m_editText = new EditText(getActivity());
return new AlertDialog.Builder(getActivity())
.setView(m_editText)
.setPositiveButton(android.R.string.ok,null)
.setNegativeButton(android.R.string.cancel, null);
.create();
}
I had the same problem. In my case it was becasue Android Studio created a template onCreateView that re-inflated a new view instead of returning the view created in onCreateDialog. onCreateView is called after onCreateDialog, so the solution was to simply reurnt the fragments view.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return this.getView();
}