主题不在android中工作

时间:2016-04-23 13:45:03

标签: android android-theme

我添加了主题更改首选项,即更改黑暗主题,原色和强调色。当我选择黑暗主题时,它只会更改设置活动主题而不是整个应用程序,原色和重音色也不会改变。 代码如下。

设置activity.java

import android.annotation.SuppressLint;
import android.os.Bundle;;
import android.preference.PreferenceFragment;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.afollestad.materialdialogs.color.ColorChooserDialog;
import com.dps.brt.Widget.Preference;
import com.dps.brt.Widget.Utils;

public class SettingActivity extends ThemedActivity implements ColorChooserDialog.ColorCallback{
@Override
protected int darkTheme() {
    return R.style.AppThemeDark;
}

@Override
protected int lightTheme() {
    return R.style.AppTheme;
}

@SuppressLint("CommitPrefEdits")
public void onColorSelection(@NonNull ColorChooserDialog colorChooserDialog, @ColorInt int color) {
    if (colorChooserDialog.isAccentMode()) {
        accentColor(color);
    } else {
        primaryColor(color);
    }
    recreate();
}
@Override
protected void onResume() {
    super.onResume();
    boolean darkTheme = isDarkTheme();
    int primaryColor = primaryColor();
    int accentColor = accentColor();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.setting);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("Setting");
    toolbar.setTitleTextColor(0xFFFFFFFF);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction().replace(R.id.tc, new SettingsFragment()).commit();
    }

}
public static class SettingsFragment extends PreferenceFragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.theme);
        findPreference("dark_theme").setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) {
                if (getActivity() != null) {
                    getActivity().recreate();
                }
                return true;
            }
        });
        Preference primaryColor = (Preference) findPreference("primary_color");
        primaryColor.setColor(((ThemedActivity) getActivity()).primaryColor(), Utils.resolveColor(getActivity(), R.attr.colorAccent));
        primaryColor.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(android.preference.Preference preference) {
                SettingActivity act = (SettingActivity) getActivity();
                if (act == null) {
                    return false;
                }
                new ColorChooserDialog.Builder(act, preference.getTitleRes())
                        .preselect(act.primaryColor())
                        .backButton(R.string.back)
                        .doneButton(R.string.done)
                        .cancelButton(android.R.string.cancel)
                        .show();
                return true;
            }
        });


        Preference accentColor = (Preference) findPreference("accent_color");
        accentColor.setColor(((ThemedActivity) getActivity()).accentColor(), Utils.resolveColor(getActivity(), R.attr.colorAccent));
        accentColor.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(android.preference.Preference preference) {
                SettingActivity act = (SettingActivity) getActivity();
                if (act == null) {
                    return false;
                }
                new ColorChooserDialog.Builder(act, preference.getTitleRes())
                        .preselect(act.accentColor())
                        .accentMode(true)
                        .backButton(R.string.back)
                        .doneButton(R.string.done)
                        .cancelButton(android.R.string.cancel)
                        .show();
                return true;
            }
        });
    }

}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {SettingActivity.this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

基本主题活动

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.res.ColorStateList;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.ColorInt;
import android.support.annotation.FloatRange;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import com.afollestad.materialdialogs.internal.ThemeSingleton;
import com.dps.brt.Widget.PrefUtils;

public abstract class ThemedActivity extends AppCompatActivity {

private boolean mLastDarkTheme;
private int mLastPrimaryColor;
private int mLastAccentColor;

@ColorInt
public static int shiftColor(@ColorInt int color, @FloatRange(from = 0.0f, to = 2.0f) float by) {
    if (by == 1f) {
        return color;
    }
    float[] hsv = new float[3];
    Color.colorToHSV(color, hsv);
    hsv[2] *= by; // value component
    return Color.HSVToColor(hsv);
}

@ColorInt
public static int shiftColorDown(@ColorInt int color) {
    return shiftColor(color, 0.9f);
}

protected int darkTheme() {
    return R.style.AppThemeDark;
}

protected int lightTheme() {
    return R.style.AppTheme;
}

public boolean isDarkTheme() {
    return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(PrefUtils.DARK_THEME, false);
}

public int primaryColor() {
    String key = PrefUtils.PRIMARY_COLOR_PREFIX;
    if (mLastDarkTheme) {
        key += "_dark";
    } else {
        key += "_light";
    }
    final int defaultColor = ContextCompat.getColor(this, mLastDarkTheme ?
            R.color.dark_theme_gray : R.color.material_indigo_500);
    return PreferenceManager.getDefaultSharedPreferences(this).getInt(key, defaultColor);
}

protected void primaryColor(int newColor) {
    String key = PrefUtils.PRIMARY_COLOR_PREFIX;
    if (mLastDarkTheme) {
        key += "_dark";
    } else {
        key += "_light";
    }
    PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(key, newColor).apply();
}

public int primaryColorDark() {
    return shiftColorDown(primaryColor());
}

public int accentColor() {
    String key = PrefUtils.ACCENT_COLOR_PREFIX;
    if (mLastDarkTheme) {
        key += "_dark";
    } else {
        key += "_light";
    }
    final int defaultColor = ContextCompat.getColor(this, R.color.material_pink_500);
    return PreferenceManager.getDefaultSharedPreferences(this).getInt(key, defaultColor);
}

protected void accentColor(int newColor) {
    String key = PrefUtils.ACCENT_COLOR_PREFIX;
    if (mLastDarkTheme) {
        key += "_dark";
    } else {
        key += "_light";
    }
    PreferenceManager.getDefaultSharedPreferences(this).edit().putInt(key, newColor).apply();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
    mLastDarkTheme = isDarkTheme();
    mLastPrimaryColor = primaryColor();
    mLastAccentColor = accentColor();
    ColorStateList sl = ColorStateList.valueOf(mLastAccentColor);
    ThemeSingleton.get().positiveColor = sl;
    ThemeSingleton.get().neutralColor = sl;
    ThemeSingleton.get().negativeColor = sl;
    ThemeSingleton.get().widgetColor = mLastAccentColor;
    setTheme(mLastDarkTheme ? darkTheme() : lightTheme());
    super.onCreate(savedInstanceState);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Sets color of entry in the system recents page
        ActivityManager.TaskDescription td = new ActivityManager.TaskDescription(
                getString(R.string.app_name),
                BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher),
                primaryColor());
        setTaskDescription(td);
    }

    if (getSupportActionBar() != null) {
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(primaryColor()));
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && hasColoredBars()) {
        final int dark = primaryColorDark();
        if (allowStatusBarColoring()) {
            getWindow().setStatusBarColor(dark);
        } else {
            getWindow().setStatusBarColor(ContextCompat.getColor(this, android.R.color.transparent));
        }
    }
}

protected boolean allowStatusBarColoring() {
    return false;
}

protected boolean hasColoredBars() {
    return true;
}

@Override
protected void onResume() {
    super.onResume();
    boolean darkTheme = isDarkTheme();
    int primaryColor = primaryColor();
    int accentColor = accentColor();
}
}

1 个答案:

答案 0 :(得分:0)

这是因为您需要在Main活动中调用recreate()。在您提供的代码中,您可以在“设置”活动中调用recreate(),这就是主题正确应用的原因。当您返回Main活动时,它不会被重新创建,只会被恢复,因此主题永远不会被应用; onCreate()未被调用。