我该如何设置按钮的代码风格,使用主题(不可绘制)?

问题描述:

我有一个静态按钮,我不得不改变代码,但是当我改变它,并在代码中指定相同的主题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)来设置样式的方式,但我的问题是使用主题

它你的按钮的风格和主题是两回事我该怎么办。要创建的按钮编程更像是设置

style="@style/ThemeOverlay.MyDarkButton" 

而非

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

您可以通过使用ContextThemeWrapper以编程方式应用主题。

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