0

我有一個靜態按鈕,我不得不改變代碼,但是當我改變它,並在代碼中指定相同的主題R.style.ThemeOverlay_MyDarkButton 我發現沒有風格得到應用。我該如何設置按鈕的代碼風格,使用主題(不可繪製)?

所以我改變了以下

<LinearLayout 
     android:id="@+id/buttons_pane" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3.0"> 
     <Button 
     android:id="@+id/button_start_verification" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1.0" 
     android:text="@string/start_phone_auth" 
     android:theme="@style/ThemeOverlay.MyDarkButton"/> 
    </LinearLayout> 

mStartButton = (Button) findViewById(R.id.button_start_verification); 

<LinearLayout 
     android:id="@+id/buttons_pane" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="horizontal" 
     android:weightSum="3.0"> 
    </LinearLayout> 

LinearLayout buttons_pane = findViewById(R.id.buttons_pane); 
    mStartButton = new Button(this, null, R.style.ThemeOverlay_MyDarkButton); 
    mStartButton.setText(R.string.start_phone_auth); 
    mStartButton.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f)); 
    mStartButton.setId(R.id.button_start_verification); 
    buttons_pane.addView(mStartButton); 

PS:我知道的使用可繪製XML作爲背景圖片 (Android Button Styling Programmatically)來設置樣式的方式,但我的問題是使用主題

回答

3

它你的按鈕的風格和主題是兩回事我該怎麼辦。要創建的按鈕編程更像是設置

style="@style/ThemeOverlay.MyDarkButton" 

而非

android:theme="@style/ThemeOverlay.MyDarkButton" 

您可以通過使用ContextThemeWrapper以編程方式應用主題。

Context themedContext = new ContextThemeWrapper(this, 
      R.style.ThemeOverlay_MyDarkButton); 
    mStartButton = new Button(themedContext); 
相關問題