- 定義屬性
- 在不同樣式中聲明屬性值
- 在佈局中使用屬性
- 再在代碼中進行切換
1. 在attr.xml文件中定義屬性顏色、字體大小等
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="tvColor1" format="color" />
<attr name="bgNormalColor" format="color" />
<attr name="tvSize1" format="dimension" />
</resources>
2. 在style.xml中設置屬性值
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="tvColor1">#333333</item>
<item name="tvSize1">12sp</item>
<item name="bgNormalColor">#fefefe</item>
</style>
<style name="AppTheme2" parent="Theme.AppCompat.DayNight">
<item name="colorPrimary">#ff0000</item>
<item name="colorPrimaryDark">#ff00ff</item>
<item name="colorAccent">#ffff00</item>
<item name="tvColor1">#ff0000</item>
<item name="tvSize1">28sp</item>
<item name="bgNormalColor">#666</item>
</style>
</resources>
3. 在佈局中使用
<?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"
android:background="?attr/bgNormalColor"
tools:context=".MainActivity">
<EditText
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_width="100dp"
android:layout_height="wrap_content" />
<Button
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:layout_width="wrap_content"
android:text="change Theme"
android:textColor="?attr/tvColor1"
android:textSize="?attr/tvSize1"
android:onClick="changeTheme"
android:layout_height="wrap_content" />
</androidx.constraintlayout.widget.ConstraintLayout>
4.在MainActivity中切換
public class MainActivity extends AppCompatActivity {
private int themeType;
@Override
protected void onCreate(Bundle savedInstanceState) {
themeType = getSharedPreferences("theme", MODE_PRIVATE).getInt("themeType", 0);
if (themeType == 0) {
setTheme(R.style.AppTheme);
} else {
setTheme(R.style.AppTheme2);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void changeTheme(View view) {
themeType = themeType == 0 ? 1 : 0;
getSharedPreferences("theme", MODE_PRIVATE).edit().putInt("themeType", themeType).commit();
recreate();
//會丟失當前頁面的狀態,需要保持的數據做持久化保持
}
}