In this post, I show how to open up a Dialog when a button in Settings is clicked and show GIF in it. I am using Kotlin in here, it is relatively easy to do the same with Java.
Create the Preference button
We will use the following XML for the button inside the preferences.xml:
<Preference android:title="Click me to open a Dialog and watch GIF"
android:key="open_up_dialog_with_gif_key"
android:summary=""/>
Create Dialog’s XML
I will create an XML file called gif_view.xml in layout directory with the following content:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/dialog_imageview_gif"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/gif"/>
</RelativeLayout>
Our Dialog will use this layout to show when clicked on the preference button.
Handling button click and showing the Dialog
Inside your SettingsFragment class, add the following code to inflate the layout and show the Dialog with the gif.
Get the handle to the Preference button
val showDialogButton = findPreference(open_up_dialog_with_gif_key) as Preference
setOnPreferenceClickListener
showDialogButton .setOnPreferenceClickListener(object : Preference.OnPreferenceClickListener {
override fun onPreferenceClick(p0: Preference?): Boolean {
val alertadd: AlertDialog.Builder? = this.let {
context?.let { it1 -> AlertDialog.Builder(it1) }
}
val factory: LayoutInflater = LayoutInflater.from(context)
val view: View = factory.inflate(R.layout.gif_view, null)
val dialogImageView = view.findViewById<ImageView>(R.id.dialog_imageview_gif)
context?.let { Glide.with(it).load(R.drawable.myGif).into(dialogImageView) }
alertadd?.setView(view)
alertadd?.apply {
setPositiveButton(R.string.close
) { dialog, id ->
}
}
alertadd?.show()
return true
}
})
NOTE: Make sure you add a GIF in Drawable directory with the name “myGif”
This is the end of the post. Please leave a comment if there is any mistake or if you know any other method of achieving this! Thank you!
For my other posts on Android, visit here. I will start posting more tips/tricks on Android soon!
For documentation on Dialogs, visit here.
0 Comments