Reputation: 39
My activity should show a dialog when launched.
This is my java class "PrivacyDialog":
public class PrivacyDialog extends AppCompatDialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Information")
.setMessage("test")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder.create();
}
}
This is the function which opens the dialog in my activity.
public void openDialog () {
PrivacyDialog privacyDialog = new PrivacyDialog();
privacyDialog.show(getSupportFragmentManager(),"PrivacyDialog");
}
My Problem:
The App crashes every time it executes the openDialog function.
Upvotes: 0
Views: 48
Reputation: 8190
You creating alert dialog inside the custom dialog, that is wrong. You should provide custom layout inside inflater.
class MyCustomDialogFragment : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Do all the stuff to initialize your custom view
return inflater.inflate(R.layout.dialog_fragment, container, false)
}
}
Dismiss
dialogFragment.dismiss();
PS: Since DialogFragment is an actual fragment you will only need to create a fragment transaction and call the show method of
val dialog: MyCustomDialogFragment = MyCustomDialogFragment()
val fm: FragmentManager = supportFragmentManager
dialog.show(fm, "fragment_dialog")
Xml layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Upvotes: 2