Generalidades

Administrador de temas de animación de Android.A veces, su aplicación de Android puede necesitar … | Autor: Iman Dolatkia | Agosto de 2021

En mi método, puedes usar código (Java o Kotlin) para cambiar el tema programáticamente. En este método, no necesitas recrear todos los recursos, también puedes usar animaciones personalizadas como ondas.

Publiqué mi enfoque como biblioteca pública aquí:

https://github.com/imandolatkia/Android-Animated-Theme-Manager

https://github.com/imandolatkia/Android-Animated-Theme-Manager

¿cómo instalar?

Agregue la siguiente línea al alcance de las dependencias en el archivo build.gradle de nivel de aplicación:

dependencies 
...
implementation "io.github.imandolatkia:animatedThemeManager:1.1.2"

¿cómo utilizar?

Si usa java, marque aquí: documentación java

1- Crea una clase abstracta heredada de AppTheme. En esta clase, cree métodos abstractos para devolver los colores relevantes de todos los elementos de la interfaz de usuario que quieran cambiarlos en cada tema. Por ejemplo, si desea cambiar el color de fondo, el color del texto y el color del icono en su primera actividad, haga lo siguiente:

interface MyAppTheme : AppTheme 
fun firstActivityBackgroundColor(context: Context): Int
fun firstActivityTextColor(context: Context): Int
fun firstActivityIconColor(context: Context): Int
// any other methods for other elements

2- Para cada tema que quieras usar en tu aplicación, crea una clase que herede de la clase (MyAppTheme) creada en el paso 1, e implementa métodos con colores o recursos relacionados, por ejemplo, si quieres tener 3 para cada tema , debes crear 3 clases e implementar métodos:

class LightTheme : MyAppTheme     override fun id(): Int  // set unique iD for each theme 
return 0
override fun firstActivityBackgroundColor(context: Context): Int
return ContextCompat.getColor(context, R.color.background_light)
override fun firstActivityTextColor(context: Context): Int
return ContextCompat.getColor(context, R.color.text_light)

override fun firstActivityIconColor(context: Context): Int
return ContextCompat.getColor(context, R.color.icon_light)

...

class NightTheme : MyAppTheme ...
class PinkTheme : MyAppTheme ...

3- Amplíe su actividad desde ThemeActivity:

MainActivity : ThemeActivity() 
...

4- Realice 2 métodos abstractos de ThemeActivity:

// to sync ui with selected theme
override fun syncTheme(appTheme: AppTheme)
// change ui colors with new appThem here
val myAppTheme = appTheme as MyAppTheme
// set background color
binder.root.setBackgroundColor(myAppTheme.firstActivityBackgroundColor(this))
//set text color
binder.text.setTextColor(myAppTheme.activityTextColor(this))

// set icons color
binder.share.setColorFilter(myAppTheme.firstActivityIconColor(this))
binder.gift.setColorFilter(myAppTheme.firstActivityIconColor(this))
...

// to get the start theme
override fun getStartTheme(): AppTheme
return LightTheme()

5- Cambiar tema ThemeManager.instance.changeTheme() método:

// set change theme click listener
binder.lightButton.setOnClickListener
ThemeManager.instance.changeTheme(LightTheme(), it)

El primer parámetro es el tema seleccionado.
El segundo parámetro es la vista donde comienza la animación desde su centro.

completo

Repita los 5 pasos anteriores, luego:

6- Extiende tus fragmentos de ThemeFragment:

MyFragment : ThemeFragment() 
...

7- Implementar el método abstracto ThemeFragment syncTheme:

// to sync ui with selected theme
override fun syncTheme(appTheme: AppTheme)
// change ui colors with new appThem here
...

✔️ Animación inversa

Si desea utilizar la animación inversa, llame a reverseChangeTheme () en lugar de changeTheme ():

binder.lightButton.setOnClickListener 
ThemeManager.instance.reverseChangeTheme(LightTheme(), it)

✔️ Cambiar la duración de la animación

Si desea cambiar la duración de la animación, agregue la duración deseada (en milisegundos) como tercer parámetro de ThemeManager.instance.changeTheme (). El valor predeterminado es 600:

binder.lightButton.setOnClickListener 
ThemeManager.instance.changeTheme(LightTheme(), it, 800)

✔️ Cambiar la posición central de la animación

Si desea iniciar la animación en otro lugar que no sea la vista en la que se hizo clic, envíe el objeto Coordinate en lugar de Ver en ThemeManager.instance.changeTheme ()

binder.lightButton.setOnClickListener 
binder.nightButton.setOnClickListener
ThemeManager.instance.changeTheme(NightTheme(), Coordinate(10, 20)

Las coordenadas de la bruja son:

Coordinate(var x: Int, var y: Int)

✔️ Observa los cambios del tema por ti mismo

Si quieres observar los cambios del tema y hacer algunas operaciones personalizadas, puedes usar el tema Livedata en cualquier segmento o actividad:

ThemeManager.instance.getCurrentLiveTheme().observe(this) 
Toast.makeText(this, "on Theme changed to $it.id()", Toast.LENGTH_SHORT).show()

✔️ Configurar oyente de animación

Si desea establecer un oyente de animación, use el método setThemeAnimationListener () en la actividad

setThemeAnimationListener(MyThemeAnimationListener(this))

La bruja MyThemeAnimationListener es:

class MyThemeAnimationListener(var context: Context) : ThemeAnimationListener
override fun onAnimationStart(animation: Animator)
Toast.makeText(context, "onAnimationStart", Toast.LENGTH_SHORT).show()
override fun onAnimationEnd(animation: Animator)
Toast.makeText(context, "onAnimationEnd", Toast.LENGTH_SHORT).show()
override fun onAnimationCancel(animation: Animator)
Toast.makeText(context, "onAnimationCancel", Toast.LENGTH_SHORT).show()
override fun onAnimationRepeat(animation: Animator)
Toast.makeText(context, "onAnimationRepeat", Toast.LENGTH_SHORT).show()

LEER  Conceptos básicos de Jetpack Compose para principiantes

Publicaciones relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Botón volver arriba