【问题标题】:Adding Button Programmatically Does not Adhere to Text Color以编程方式添加按钮不遵守文本颜色
【发布时间】:2015-09-02 12:52:40
【问题描述】:

我的按钮样式如下:

<style name="ButtonAppTheme" parent="android:Widget.Holo.Light.Button">
      <!-- ORIGINAL: <item name="android:background">@drawable/apptheme_btn_default_holo_light</item> -->
      <item name="android:background">@drawable/x_button_background</item>
      <item name="android:textColor">@drawable/x_button_text</item>
      <item name="android:textSize">@dimen/master_fontsize_mid</item>
      <item name="android:paddingLeft">@dimen/button_padleft</item>
      <item name="android:paddingRight">@dimen/button_padright</item>
      <item name="android:singleLine">true</item>
  </style>

在主题中设置如下:

<item name="android:buttonStyle">@style/ButtonAppTheme</item>

我在我的应用程序清单中设置了这个主题。但是,当我像这样以编程方式添加按钮时:

btn = new Button(activity);
LayoutParams params = new LayoutParams(R.dimen.button_height, LayoutParams.MATCH_PARENT);
btn.setLayoutParams(params);
btn.setText("MyButton");
layout.addView(btn);

背景可绘制对象渲染得很好,但文本是白色的,而不是应有的可绘制对象(灰色和红色取决于状态)。如何确保我以编程方式添加的按钮完全符合这种风格?

【问题讨论】:

  • 尝试以这种方式初始化按钮:btn = new Button(activity,null,R.style.ButtonAppTheme);
  • @HareshChhelana 如果我以这种方式创建按钮,我什至无法获得可绘制边框。

标签: android xml button themes


【解决方案1】:

使用以下代码:

 <Button
     android:id="@+id/button1"
     style="@style/ButtonAppTheme"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Button" />

以编程方式,

Button b = new Button(getApplicationContext(), null, R.style.ButtonAppTheme);

【讨论】:

  • android.widget.Button 似乎没有 setStyle 方法。
  • 问题是关于以编程方式添加按钮,而不是通过 xml。
  • 这是由上面的@HareshChhelana 建议的。它不起作用。另外,我已经在应用程序和基本上下文中尝试过这个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-02
  • 2015-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
  • 2015-06-30
相关资源
最近更新 更多