Подтвердить что ты не робот

Android - Изменить тему приложения на onClick

Я знаю, что есть способ изменить тему приложения по умолчанию при нажатии кнопки. Разработчики Blackmart сделали это. Ive уже искал Google, как 1000 страниц, но я нашел именно это (не работает)

getApplication().setTheme(Theme.Holo)

Как я уже создал новый стиль в res/values ​​/styles.xml, есть ли другой способ его динамического изменения? Даже перезагрузка приложения?

4b9b3361

Ответ 1

Следующий блог может решить вашу проблему:

http://mrbool.com/how-to-change-the-layout-theme-of-an-android-application/25837

Копирование кода блога для быстрой справки:

Предполагая, что вы уже определили следующие три темы в XML файле R.style.FirstTheme, R.style.SecondTheme и R.style.ThirdTheme

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
public class ChangeThemeActivity extends Activity implements OnClickListener
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        Utils.onActivityCreateSetTheme(this);
        setContentView(R.layout.main);

                    findViewById(R.id.button1).setOnClickListener(this);
          findViewById(R.id.button2).setOnClickListener(this);
          findViewById(R.id.button3).setOnClickListener(this);
    }
     @Override
     public void onClick(View v)
     {
          // TODO Auto-generated method stub
          switch (v.getId())
          {
          case R.id.button1:
          Utils.changeToTheme(this, Utils.THEME_DEFAULT);
          break;
          case R.id.button2:
          Utils.changeToTheme(this, Utils.THEME_WHITE);
          break;
          case R.id.button3:
          Utils.changeToTheme(this, Utils.THEME_BLUE);
          break;
          }
     }
}

Давайте напишем приведенный ниже код в файле "Utils":

import android.app.Activity;
import android.content.Intent;
public class Utils
{
     private static int sTheme;
     public final static int THEME_DEFAULT = 0;
     public final static int THEME_WHITE = 1;
     public final static int THEME_BLUE = 2;
     /**
      * Set the theme of the Activity, and restart it by creating a new Activity of the same type.
      */
     public static void changeToTheme(Activity activity, int theme)
     {
          sTheme = theme;
          activity.finish();
activity.startActivity(new Intent(activity, activity.getClass()));
     }
     /** Set the theme of the activity, according to the configuration. */
     public static void onActivityCreateSetTheme(Activity activity)
     {
          switch (sTheme)
          {
          default:
          case THEME_DEFAULT:
              activity.setTheme(R.style.FirstTheme);
              break;
          case THEME_WHITE:
              activity.setTheme(R.style.SecondTheme);
              break;
          case THEME_BLUE:
              activity.setTheme(R.style.Thirdheme);
              break;
          }
     }
}

Надеюсь, что это поможет...

ИЗМЕНИТЬ 1:

следующая причина AlertDialog не принимает пользовательскую тему:

Реализация в Builder.create() есть:

public AlertDialog create() {
    final AlertDialog dialog = new AlertDialog(P.mContext);
    P.apply(dialog.mAlert);
    [...]
}

который вызывает конструктор "AlertDialog", созданный не темой, который выглядит следующим образом:

protected AlertDialog(Context context) {
    this(context, com.android.internal.R.style.Theme_Dialog_Alert);
}

В AlertDialog есть второй конструктор для изменения тем:

protected AlertDialog(Context context, int theme) {
    super(context, theme);
    [...]
}

что Builder просто не вызывает.

Ознакомьтесь со следующим сообщением для более релевантных исправлений.

Как изменить тему для AlertDialog

Ниже приведен наиболее проголосовавший ответ:

  new AlertDialog.Builder(
  new ContextThemeWrapper(context, android.R.style.Theme_Dialog))