是否可以在不使用XML的情况下为主题应用动画?过去,我使用的是 styles.xml ,但我希望它是动态进行的。
预期结果
当前结果
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Material.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
<!-- dark mode Settings theme. -->
<style name="MyDarkSettingsTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@null</item>
<item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>
<!-- light mode Settings theme. -->
<style name="MyLightSettingsTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:windowBackground">@null</item>
<item name="android:windowAnimationStyle">@style/WindowAnimationTransition</item>
</style>
<style name="WindowAnimationTransition">
<item name="android:windowEnterAnimation">@android:anim/fade_in</item>
<item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>
</resources>
活动
class SettingsActivity : AppCompatActivity(), SettingsFragment.PreferenceXchangeListener {
private var mCurrentValue: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
val mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
mCurrentValue = mSharedPreferences.getBoolean("preference_a", false)
if (mCurrentValue) {
setTheme(R.style.MyDarkSettingsTheme)
} else {
setTheme(R.style.MyLightSettingsTheme)
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val viewllSettingsContainer = findViewById<LinearLayout>(R.id.settings_container)
val root = viewllSettingsContainer.rootView
// Set the background color upon Activity launch and Theme change
if (mCurrentValue) {
root.setBackgroundColor(Color.BLACK)
} else {
root.setBackgroundColor(Color.WHITE)
}
val mToolbar = findViewById<Toolbar>(R.id.toolbar_1line)
setSupportActionBar(mToolbar)
val mTitle = this.findViewById<TextView>(R.id.toolbar_1line_title)
mTitle.text = "Preferences"
mTitle.setTextColor(Color.WHITE)
val settingsFragment = SettingsFragment()
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, settingsFragment)
.commit()
}
// callback method for changing preference. It's only called if "preference_a" has changed
override fun onXchange(value:Boolean) {
// if value differs from previous Theme, recreate Activity
when {
mCurrentValue != value -> {
mCurrentValue = value
recreate()
}
}
}
}
片段
anim / fade_in.xml
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="1.0" android:toAlpha="0.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>