2014-10-10 46 views
5

我想知道應用程序中的活動應用了哪個主題。以編程方式獲取應用於活動的主題值

通常我們是通過使用

setTheme(android.R.style.Theme_Light); 

這裏我們指定樣式設置爲主題,作爲這樣我們才能能夠得到完全適用於編程活動的特定樣式類型。

感謝

回答

15

上下文類有一個叫做getThemeResId不錯的方法,但是它是私有因此你需要使用反射。

下面是一個例子:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_my); 

    Log.e("TAG", "Def theme: " + R.style.AppTheme); 
    Log.e("TAG", "Light theme: " + android.R.style.Theme_Light); 
    Log.e("TAG", "Current theme id: " + getThemeId()); 

    setTheme(android.R.style.Theme_Light); 
    Log.e("TAG", "Current theme id: " + getThemeId()); 
} 

int getThemeId() { 
    try { 
     Class<?> wrapper = Context.class; 
     Method method = wrapper.getMethod("getThemeResId"); 
     method.setAccessible(true); 
     return (Integer) method.invoke(this); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return 0; 
} 
+0

謝謝。它的正常工作 – 2014-10-13 06:27:22

+0

好的,謝謝 – 2017-10-18 09:13:25

相關問題