Android에서 런타임시 현재 테마를 변경하는 방법
이 질문에는 이미 답변이 있습니다.
- 테마 3 답변 의 사용자 선택 구현
사용자가 전체 응용 프로그램에 적용 할 테마를 선택할 수있는 PreferenceActivity를 만들었습니다.
사용자가 테마를 선택하면이 코드가 실행됩니다.
if (...) {
getApplication().setTheme(R.style.BlackTheme);
} else {
getApplication().setTheme(R.style.LightTheme);
}
그러나 디버거를 사용하여 코드가 실행되고 있는지 확인했지만 사용자 인터페이스에서 변경된 내용을 볼 수 없습니다.
테마는에 정의되어 res/values/styles.xml
있으며 Eclipse에는 오류가 표시되지 않습니다.
<resources>
<style name="LightTheme" parent="@android:style/Theme.Light">
</style>
<style name="BlackTheme" parent="@android:style/Theme.Black">
</style>
</resources>
발생할 수있는 일과 해결 방법에 대한 아이디어가 있습니까? setTheme
코드의 특정 지점에서 전화해야합니까 ? 도움이된다면 내 응용 프로그램은 여러 활동으로 구성됩니다.
모든 활동에 대해 한 번 설정 한 방법도보고 싶습니다. 그러나 지금까지 나는 당신이보기를 표시하기 전에 각 활동에서 설정해야한다는 것을 알고 있습니다.
참조를 위해 이것을 확인하십시오 :
http://www.anddev.org/applying_a_theme_to_your_application-t817.html
편집 (해당 포럼에서 복사) :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Call setTheme before creation of any(!) View.
setTheme(android.R.style.Theme_Dark);
// ...
setContentView(R.layout.main);
}
당신은, 이미 존재하는 활동의 전화를 테마를 변경하려면 recreate()
후 setTheme()
.
참고 :에서 onCreate()
무한 테마 를 피하기 위해 테마를 변경하는 경우에는 재 작성을 호출하지 마십시오 .
recreate()
( TPReal 에서 언급 했듯이 ) 현재 활동 만 다시 시작하지만 이전 활동은 여전히 스택에 있으며 테마는 적용되지 않습니다.
따라서이 문제에 대한 또 다른 해결책은 다음과 같이 작업 스택을 완전히 다시 작성하는 것입니다.
TaskStackBuilder.create(getActivity())
.addNextIntent(new Intent(getActivity(), MainActivity.class))
.addNextIntent(getActivity().getIntent())
.startActivities();
편집하다:
UI 또는 다른 곳에서 테마 변경을 수행 한 후 위의 코드를 입력하십시오. 모든 활동에는 아마도 일부 부모 활동에서 setTheme()
전에 호출 된 메소드가 있어야 onCreate()
합니다. 에서 선택한 테마를 저장하고 SharedPreferences
읽은 다음 setTheme()
방법을 사용하여 설정 하는 일반적인 방법이기도합니다 .
나는 같은 문제가 있지만 해결책을 찾았습니다.
public class EditTextSmartPhoneActivity extends Activity implements DialogInterface.OnClickListener
{
public final static int CREATE_DIALOG = -1;
public final static int THEME_HOLO_LIGHT = 0;
public final static int THEME_BLACK = 1;
int position;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
position = getIntent().getIntExtra("position", -1);
switch(position)
{
case CREATE_DIALOG:
createDialog();
break;
case THEME_HOLO_LIGHT:
setTheme(android.R.style.Theme_Holo_Light);
break;
case THEME_BLACK:
setTheme(android.R.style.Theme_Black);
break;
default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private void createDialog()
{
/** Options for user to select*/
String choose[] = {"Theme_Holo_Light","Theme_Black"};
AlertDialog.Builder b = new AlertDialog.Builder(this);
/** Setting a title for the window */
b.setTitle("Choose your Application Theme");
/** Setting items to the alert dialog */
b.setSingleChoiceItems(choose, 0, null);
/** Setting a positive button and its listener */
b.setPositiveButton("OK",this);
/** Setting a positive button and its listener */
b.setNegativeButton("Cancel", null);
/** Creating the alert dialog window using the builder class */
AlertDialog d = b.create();
/** show dialog*/
d.show();
}
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
AlertDialog alert = (AlertDialog)dialog;
int position = alert.getListView().getCheckedItemPosition();
finish();
Intent intent = new Intent(this, EditTextSmartPhoneActivity.class);
intent.putExtra("position", position);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
비슷한 문제가 있었고 이런 식으로 해결했습니다 ..
@Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().hasExtra("bundle") && savedInstanceState==null){
savedInstanceState = getIntent().getExtras().getBundle("bundle");
}
//add code for theme
switch(theme)
{
case LIGHT:
setTheme(R.style.LightTheme);
break;
case BLACK:
setTheme(R.style.BlackTheme);
break;
default:
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//code
}
이 코드는 활동 저장 번들을 다시 작성하고 테마를 변경하기위한 것입니다. 자신의 onSaveInstanceState (Bundle outState)를 작성해야합니다. API-11부터는 recreate () 메소드를 대신 사용할 수 있습니다
Bundle temp_bundle = new Bundle();
onSaveInstanceState(temp_bundle);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("bundle", temp_bundle);
startActivity(intent);
finish();
'super.onCreate ()' 및 'setContentView ()' 메소드 를 호출하기 전에 테마를 설정해야합니다 .
Check out this link for applying new theme to whole application at runtime.
Instead of
getApplication().setTheme(R.style.BlackTheme);
use
setTheme(R.style.BlackTheme);
My code: in onCreate() method:
super.onCreate(savedInstanceState);
if(someExpression) {
setTheme(R.style.OneTheme);
} else {
setTheme(R.style.AnotherTheme);
}
setContentView(R.layout.activity_some_layout);
Somewhere (for example, on a button click):
YourActivity.this.recreate();
You have to recreate activity, otherwise - change won't happen
This is what i have created for Material Design. May it will helpful you.
Have a look for MultipleThemeMaterialDesign
I know that i am late but i would like to post a solution here: Check the full source code here. This is the code i used when changing theme using preferences..
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(this);
String themeName = pref.getString("prefSyncFrequency3", "Theme1");
if (themeName.equals("Africa")) {
setTheme(R.style.AppTheme);
} else if (themeName.equals("Colorful Beach")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.beach);
} else if (themeName.equals("Abstract")) {
//Toast.makeText(this, "set theme", Toast.LENGTH_SHORT).show();
setTheme(R.style.abstract2);
} else if (themeName.equals("Default")) {
setTheme(R.style.defaulttheme);
}
This way work for me:
@Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(GApplication.getInstance().getTheme());
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Then you want to change a new theme:
GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();
You can finish the Acivity and recreate it afterwards in this way your activity will be created again and all the views will be created with the new theme.
Call SetContentView(Resource.Layout.Main) after setTheme().
This had no effect for me:
public void changeTheme(int newTheme) {
setTheme(newTheme);
recreate();
}
But this worked:
int theme = R.style.default;
protected void onCreate(Bundle savedInstanceState) {
setTheme(this.theme);
super.onCreate(savedInstanceState);
}
public void changeTheme(int newTheme) {
this.theme = newTheme;
recreate();
}
참고URL : https://stackoverflow.com/questions/2482848/how-to-change-current-theme-at-runtime-in-android
'development' 카테고리의 다른 글
Visual Studio 2015는 매우 느립니다 (0) | 2020.06.18 |
---|---|
main의 올바른 선언은 무엇입니까? (0) | 2020.06.18 |
정적 컨텐츠를 제공하기위한 서블릿 (0) | 2020.06.18 |
JavaScript에서 문자열을 연결하는 가장 효율적인 방법은 무엇입니까? (0) | 2020.06.18 |
Firebug에서 CSS 변경 사항을 저장할 수없는 이유는 무엇입니까? (0) | 2020.06.18 |