首页 > 代码库 > Android 学习笔记之切换主题

Android 学习笔记之切换主题

首先要有主题颜色

theme_color.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <resources>
 3 
 4     <!---->
 5     <color name="red">#FF6347</color>
 6     <color name="dark_red">#F4511E</color>
 7     <color name="accent_red">#FF5722</color>
 8 
 9     <!---->
10     <color name="brown">#795548</color>
11     <color name="dark_brown">#5D4037</color>
12     <color name="accent_brown">#795548</color>
13 
14     <!---->
15     <color name="blue">#3F51B5</color>
16     <color name="dark_blue">#303F9F</color>
17     <color name="accent_blue">#3F51B5</color>
18 
19     <!--蓝灰-->
20     <color name="blue_grey">#607D8B</color>
21     <color name="dark_blue_grey">#455A64</color>
22     <color name="accent_blue_grey">#607D8B</color>
23 
24     <!---->
25     <color name="yellow">#FF9800</color>
26     <color name="dark_yellow">#F57C00</color>
27     <color name="accent_yellow">#FF9800</color>
28 
29     <!---->
30     <color name="deep_purple">#673AB7</color>
31     <color name="dark_deep_purple">#512DA8</color>
32     <color name="accent_deep_purple">#7C4DFF</color>
33 
34     <!--粉红-->
35     <color name="pink">#E91E63</color>
36     <color name="dark_pink">#C2185B</color>
37     <color name="accent_pink">#FF5722</color>
38 
39     <!--绿-->
40     <color name="green">#4CAF50</color>
41     <color name="dark_green">#388E3C</color>
42     <color name="accent_green">#4CAF50</color>
43 
44 </resources>

以及主题

theme_syyles.xml

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <resources>
 3 
 4     <!--<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">-->
 5         <!--<item name="android:textColorPrimary">@color/text_black</item>-->
 6         <!--&lt;!&ndash;主背景色&ndash;&gt;-->
 7         <!--<item name="android:windowBackground">@android:color/white</item>-->
 8     <!--</style>-->
 9 
10     <!--蓝色主题-->
11     <style name="BlueTheme" parent="AppTheme">
12         <item name="colorPrimary">@color/blue</item>
13         <item name="colorPrimaryDark">@color/dark_blue</item>
14         <item name="colorAccent">@color/accent_blue</item>
15     </style>
16 
17     <!--蓝灰色主题-->
18     <style name="BlueGreyTheme" parent="AppTheme">
19         <item name="colorPrimary">@color/blue_grey</item>
20         <item name="colorPrimaryDark">@color/dark_blue_grey</item>
21         <item name="colorAccent">@color/accent_blue_grey</item>
22     </style>
23 
24     <!--红色主题-->
25     <style name="RedTheme" parent="AppTheme">
26         <item name="colorPrimary">@color/red</item>
27         <item name="colorPrimaryDark">@color/dark_red</item>
28         <item name="colorAccent">@color/accent_red</item>
29     </style>
30 
31     <!--棕色主题-->
32     <style name="BrownTheme" parent="AppTheme">
33         <item name="colorPrimary">@color/brown</item>
34         <item name="colorPrimaryDark">@color/dark_brown</item>
35         <item name="colorAccent">@color/accent_brown</item>
36     </style>
37 
38     <!--黄色主题-->
39     <style name="YellowTheme" parent="AppTheme">
40         <item name="colorPrimary">@color/yellow</item>
41         <item name="colorPrimaryDark">@color/dark_yellow</item>
42         <item name="colorAccent">@color/accent_yellow</item>
43     </style>
44 
45     <!--紫色主题-->
46     <style name="DeepPurpleTheme" parent="AppTheme">
47         <item name="colorPrimary">@color/deep_purple</item>
48         <item name="colorPrimaryDark">@color/dark_deep_purple</item>
49         <item name="colorAccent">@color/accent_deep_purple</item>
50     </style>
51 
52     <!--粉红色主题-->
53     <style name="PinkTheme" parent="AppTheme">
54         <item name="colorPrimary">@color/pink</item>
55         <item name="colorPrimaryDark">@color/dark_pink</item>
56         <item name="colorAccent">@color/accent_pink</item>
57     </style>
58 
59     <!--绿色主题-->
60     <style name="GreenTheme" parent="AppTheme">
61         <item name="colorPrimary">@color/green</item>
62         <item name="colorPrimaryDark">@color/dark_green</item>
63         <item name="colorAccent">@color/accent_green</item>
64     </style>
65 </resources>

 

MainActivity.java

 1 package com.example.myapplication;
 2 
 3 import android.content.Intent;
 4 import android.support.v7.app.AlertDialog;
 5 import android.support.v7.app.AppCompatActivity;
 6 import android.os.Bundle;
 7 import android.view.LayoutInflater;
 8 import android.view.View;
 9 import android.view.ViewGroup;
10 import android.widget.AdapterView;
11 import android.widget.BaseAdapter;
12 import android.widget.GridView;
13 import android.widget.ImageView;
14 
15 import java.util.ArrayList;
16 import java.util.List;
17 
18 public class MainActivity extends AppCompatActivity {
19     private List<Integer> listColor  = new ArrayList();;
20     @Override
21     protected void onCreate(Bundle savedInstanceState) {
22         ThemeUtils.changTheme(this);
23         super.onCreate(savedInstanceState);
24         setContentView(R.layout.activity_main);
25         findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
26             @Override
27             public void onClick(View view) {
28                 initt();
29             }
30         });
31 
32     }
33 
34     /**
35      * 方法
36      */
37     private void initt() {
38         //为LIST添加数值
39         listColor.add(R.color.red);
40         listColor.add(R.color.brown);
41         listColor.add(R.color.blue);
42         listColor.add(R.color.blue_grey);
43         listColor.add(R.color.yellow);
44         listColor.add(R.color.deep_purple);
45         listColor.add(R.color.pink);
46         listColor.add(R.color.green);
47         //构建对话框
48         AlertDialog.Builder alertdoalog = new AlertDialog.Builder(this);
49         alertdoalog.setTitle("切换主题");
50         //绑定 布局
51         View view = LayoutInflater.from(this).inflate(R.layout.theme_colors_panel_layout,null);
52         //初始化网格视图
53         GridView gridview = (GridView) view.findViewById(R.id.grid);
54         //填充Adapter
55         ThemeAdapter  themeadapter = new ThemeAdapter(MainActivity.this,listColor,R.layout.theme_colors_image_layout);
56         //set当前点击
57         themeadapter.setCheckItem((Integer) SharedPreferenceUtil.get(this,"key",0));
58         
59         gridview.setAdapter(themeadapter);
60         gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
61             @Override
62             public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
63                 //保存当前点击
64                 SharedPreferenceUtil.put(MainActivity.this,"key",i);
65                 //重新启动
66                 startActivity(new Intent(MainActivity.this,MainActivity.class));
67                 //关闭
68                 finish();
69             }
70         });
71         alertdoalog.setView(view);
72         alertdoalog.show();
73     }
74 }
ThemeUtils.java
 1 package com.example.myapplication;
 2 
 3 import android.app.Activity;
 4 
 5 /**
 6  * 主题工具类
 7  */
 8 public class ThemeUtils {
 9 
10     /**
11      * 修改主题
12      * @param activity
13      */
14     public static void changTheme(Activity activity){
15         if (activity == null)
16             return;
17 
18         int position = (int) SharedPreferenceUtil.get(activity,"key", 0);
19         int style = R.style.BlueTheme;
20         switch (position){
21             case 0:
22                 style = R.style.YellowTheme;
23                 break;
24             case 1:
25                 style = R.style.BrownTheme;
26                 break;
27             case 2:
28                 style = R.style.BlueTheme;
29                 break;
30             case 3:
31                 style = R.style.BlueGreyTheme;
32                 break;
33             case 4:
34                 style = R.style.YellowTheme;
35                 break;
36             case 5:
37                 style = R.style.DeepPurpleTheme;
38                 break;
39             case 6:
40                 style = R.style.PinkTheme;
41                 break;
42             case 7:
43                 style = R.style.GreenTheme;
44                 break;
45             default:
46                 break;
47         }
48         activity.setTheme(style);
49     }
50 
51 }
SharedPreferenceUtil.java
package com.example.myapplication;

import android.content.Context;
import android.content.SharedPreferences;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;

/**
 * Stay  hungry , Stay  foolish

 * Copyright(c) 2016 www.wuxianedu.com Inc. All rights reserved.
 */
public class SharedPreferenceUtil {
    public static final String FILE_NAME = "share_data"; // SharedPreference操作的文件

    /**
     * 保存数据的方法,我们需要拿到保存数据的具体类型,然后根据类型调用不同的保存方法
     * @param context
     * @param key
     * @param object
     */
    public static void put(Context context, String key, Object object) {

        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();

        if (object instanceof String) {
            editor.putString(key, (String) object);
        } else if (object instanceof Integer) {
            editor.putInt(key, (Integer) object);
        } else if (object instanceof Boolean) {
            editor.putBoolean(key, (Boolean) object);
        } else if (object instanceof Float) {
            editor.putFloat(key, (Float) object);
        } else if (object instanceof Long) {
            editor.putLong(key, (Long) object);
        } else {
            editor.putString(key, object.toString());
        }

        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 得到保存数据的方法,我们根据默认值得到保存的数据的具体类型,然后调用相对于的方法获取值
     * 
     * @param context
     * @param key
     * @param defaultObject
     * @return
     */
    public static Object get(Context context, String key, Object defaultObject) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);

        if (defaultObject instanceof String || defaultObject==null) {
            return sp.getString(key, (String) defaultObject);
        } else if (defaultObject instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObject);
        } else if (defaultObject instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObject);
        } else if (defaultObject instanceof Float) {
            return sp.getFloat(key, (Float) defaultObject);
        } else if (defaultObject instanceof Long) {
            return sp.getLong(key, (Long) defaultObject);
        }
        return null;
    }

    /**
     * 移除某个key值已经对应的值
     * 
     * @param context
     * @param key
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 返回所有的键值对
     *
     * @param context
     * @return
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.getAll();
    }

    /**
     * 清除所有数据
     *
     * @param context
     */
    public static void clearAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        SharedPreferencesCompat.apply(editor);
    }

    /**
     * 查询某个key是否已经存在
     * 
     * @param context
     * @param key
     * @return
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
                Context.MODE_PRIVATE);
        return sp.contains(key);
    }

    /**
     * 创建一个解决SharedPreferencesCompat.apply方法的一个兼容类
     */
    private static class SharedPreferencesCompat {
        private static final Method sApplyMethod = findApplyMethod();

        /**
         * 反射查找apply的方法
         * @return
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        private static Method findApplyMethod() {
            try {
                Class clz = SharedPreferences.Editor.class;
                return clz.getMethod("apply");
            } catch (NoSuchMethodException e) {
            }

            return null;
        }

        /**
         * 如果找到则使用apply执行,否则使用commit
         * 
         * 里面所有的commit操作使用了SharedPreferencesCompat.apply进行了替代,目的是尽可能的使用apply代替commit
         * 首先说下为什么,因为commit方法是同步的,并且我们很多时候的commit操作都是UI线程中,毕竟是IO操作,尽可能异步;
         * 所以我们使用apply进行替代,apply异步的进行写入;
         * @param editor
         */
        public static void apply(SharedPreferences.Editor editor) {
            try {
                if (sApplyMethod != null) {
                    sApplyMethod.invoke(editor);
                    return;
                }
            } catch (IllegalArgumentException e) {
            } catch (IllegalAccessException e) {
            } catch (InvocationTargetException e) {
            }
            editor.commit();
        }
    }
}
ThemeAdapter.java
 1 package com.example.myapplication;
 2 
 3 import android.content.Context;
 4 import android.view.LayoutInflater;
 5 import android.view.View;
 6 import android.view.ViewGroup;
 7 import android.widget.BaseAdapter;
 8 import android.widget.ImageView;
 9 
10 import java.util.List;
11 
12 /**
13  * Created by Administrator on 2016/12/5.
14  */
15 public class ThemeAdapter extends BaseCustomAdapter {
16     private int checkItem;
17     public ThemeAdapter(Context context, List data, int layoutResId) {
18         super(context, data, layoutResId);
19     }
20 
21     @Override
22     public View getCustomView(int position, View convertView) {
23         ImageView imageView1 = (ImageView) convertView.findViewById(R.id.img_1);
24         ImageView imageView2 = (ImageView) convertView.findViewById(R.id.img_2);
25         imageView1.setImageResource((Integer) data.get(position));
26         if(checkItem == position){
27             imageView2.setImageResource(R.mipmap.ic_done_white);
28         }
29         return convertView;
30     }
31 
32     public void setCheckItem(int checkItem) {
33         this.checkItem = checkItem;
34     }
35 }
BaseCustomAdapter.java
  1 package com.example.myapplication;
  2 
  3 import android.content.Context;
  4 import android.view.LayoutInflater;
  5 import android.view.View;
  6 import android.view.ViewGroup;
  7 import android.widget.BaseAdapter;
  8 
  9 
 10 import java.util.List;
 11 
 12 /**
 13  *
 14  *
 15  * 2015年10月26日,0026.
 16  * 所有BaseAdapter的直接父类
 17  * @param <E>
 18  */
 19 public abstract class BaseCustomAdapter<E> extends BaseAdapter {
 20 
 21     protected LayoutInflater layoutInflater;
 22 
 23     protected List<E> data;
 24 
 25     protected int layoutResId; // item id
 26 
 27     public BaseCustomAdapter(Context context, List<E> data, int layoutResId) {
 28         this.layoutResId = layoutResId;
 29         this.data=http://www.mamicode.com/data;
 30         this.layoutInflater = LayoutInflater.from(context);
 31     }
 32 
 33 
 34 
 35     public void addAll(List<E> data){
 36         this.data.addAll(data);
 37         notifyDataSetChanged();
 38 
 39     }
 40 
 41     public void addAll(int location,List<E> data){
 42         this.data.addAll(location, data);
 43         notifyDataSetChanged();
 44     }
 45 
 46     public void add(E e){
 47         this.data.add(e);
 48         notifyDataSetChanged();
 49     }
 50 
 51     public void add(int location,E e){
 52         this.data.add(location, e);
 53         notifyDataSetChanged();
 54     }
 55 
 56     public void remove(int location){
 57         this.data.remove(location);
 58         notifyDataSetChanged();
 59     }
 60 
 61     public void remove(E e){
 62         this.data.remove(e);
 63         notifyDataSetChanged();
 64     }
 65 
 66     public void removeAll(List<E> data){
 67         this.data.removeAll(data);
 68         notifyDataSetChanged();
 69     }
 70 
 71     @Override
 72     public int getCount() {
 73         return data.size();
 74     }
 75 
 76     @Override
 77     public E getItem(int position) {
 78         return data.get(position);
 79     }
 80 
 81     @Override
 82     public long getItemId(int position) {
 83         return position;
 84     }
 85 
 86     @Override
 87     public View getView(int position, View convertView, ViewGroup parent) {
 88         if(convertView == null){
 89             convertView = layoutInflater.inflate(layoutResId,null);
 90             getListener(convertView);
 91         }
 92         getCustomView(position, convertView);
 93         return convertView;
 94     }
 95 
 96     public abstract View getCustomView(int position, View convertView);
 97 
 98     /**
 99      * 如果需要点击事件  重写此方法
100      */
101     protected void getListener(View convertView){}
102 }

 好了,到这里切换主题就可以实现了

Android 学习笔记之切换主题