프로그래밍 방식으로 활동 테마 변경


121

특정 경우에 내 활동에서 대화 테마를 제거해야하지만 작동하지 않는 것 같습니다. 여기에 예가 있습니다.

첫 번째 활동 :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startActivity(new Intent(MainActivity.this, SecondActivity.class));
}

두 번째 활동 :

public void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setTheme(android.R.style.Theme);
    setContentView(R.layout.activity_second);
}

매니페스트 발췌 :

 <activity android:name="SecondActivity" android:theme="@android:style/Theme.Dialog"></activity>

내가 실행할 때 여전히 대화 테마입니다.

API10

감사.

답변:


183

마찬가지로 문서는 말을 당신은 전화를해야 setTheme모든보기 출력하기 전에. 처리에 super.onCreate()참여 하는 것 같습니다 view.

따라서 테마 사이를 동적으로 전환하려면 다음 과 같이 setTheme먼저 호출 super.onCreate하면됩니다.

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

스택 Android 5.1을 사용하는 MotoG (v1)에서 나를 위해 작동합니다. 작동하지 않는 경우 장치 + 안드로이드 버전을 공유하십시오.
lenrok258

여기에 설명 된대로 테마를 정의해야했습니다. stackoverflow.com/a/44236460/3211335 그런 다음이 답변에 설명 된대로 설정해야합니다. 잘 작동합니다.
LaloLoop

어쨌든 우리가 대신 페이지 당 세트 테마의 ... 한 번만 테마가 설정할 수 있나요
gayan1991

공유 환경 설정을 사용하여 테마를 저장하지만 앱을 다시 시작하면 잠시 첫 번째 테마가 나타난 다음 두 번째 테마가 표시됩니다!
모하마드 Afrashteh

1
@ gayan1991 당신은 당신의 테마를 정의하는 다른 활동을 사용하여 모든 활동이 하나의 예를 확장하는 다른 만들 수 있습니다 pastebin.com/r93qrRDG 서식을 더 가지고 사용 페이스트 빈 : 편집
SocialSupaCrew

46

user1462299의 응답은 훌륭하게 작동하지만 fragments를 포함 하면 원래 활동 테마를 사용합니다. 테마를 모든 조각에도 적용하려면 대신 Context 의 getTheme () 메서드를 재정의 할 수 있습니다 .

@Override
public Resources.Theme getTheme() {
    Resources.Theme theme = super.getTheme();
    if(useAlternativeTheme){
        theme.applyStyle(R.style.AlternativeTheme, true);
    }
    // you could also use a switch if you have many themes that could apply
    return theme;
}

더 이상 onCreate () 메서드에서 setTheme ()를 호출 할 필요가 없습니다. 이러한 방식으로이 컨텍스트 내에서 현재 테마를 가져 오기 위해 모든 요청을 재정의합니다.


2
@ 반대표를 던진 사람 : 내 응답에 대해 싫어하는 점을 설명해 주시겠습니까?
Björn Kechel 2016

getTheme ()가 Activity 또는 각 Fragment에서 재정의되어야합니까? 나는 이것을 Activity에서 구현했지만 Fragments는 여전히 원래 Activity 테마를 사용하고 있습니다.
saltandpepper

@saltandpepper 활동에서 재정의하는 것으로 충분합니다. 조각 코드와 레이아웃이 다시 변경되지 않도록하십시오.
Björn Kechel

이것은 나를 위해 작동하지 않았지만 stackoverflow.com/a/15496425/494179에 제공된 답변은 작동했습니다 .
saltandpepper

2
좋은 점 user1269737이므로 무거운 계산이 없는지 확인해야합니다. 단순한 조건 케이스 내에서 스타일을 반환하는 것만으로는 성능에 영향을 미치지 않습니다.
Björn Kechel

12

내가 늦었 음을 알고 있지만 여기에 해결책을 게시하고 싶습니다 . 여기
에서 전체 소스 코드를 확인 하십시오 .
환경 설정을 사용하여 테마를 변경할 때 사용한 코드입니다 ..

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);

}

setcontentview 앞에 코드를 넣어야합니다.

즐거운 코딩!


왜? 대답은 corect ?!
dondondon

공유 환경 설정을 사용하여 테마를 저장하지만 앱을 다시 시작하면 잠시 첫 번째 테마가 나타난 다음 두 번째 테마가 표시됩니다!
모하마드 Afrashteh

0

이것은 나를 위해 잘 작동합니다.

theme.applyStyle(R.style.AppTheme, true)

용법:

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //The call goes right after super.onCreate() and before setContentView()
    theme.applyStyle(R.style.AppTheme, true)
    setContentView(layoutId)
    onViewCreated(savedInstanceState)
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.