开发者

How can I change a button style dynamically in Android? [duplicate]

This question already has answers here: How to programmatically set style attribute in a view (11 answers) Closed 8 years ago.

I want to change the style of a button dynamically, i.e. in Java code, something like:

((Button)findViewById(id)).setStyle("@styles/foo")

<resources>
    <style name="foo">
        <item name="android:adjustViewBounds">true</item>开发者_StackOverflow;
        <item name="android:maxHeight">100px</item>
        <item name="android:maxWidth">200px</item>
    </style>
</resources>

I have not seen nothing like setStyle, so:

do I have to change every single property or I can change the whole style?


To assign a style like this

<style name="ButtonHOLO" parent="android:Widget.Button">
      <item name="android:background">@drawable/btn_default_holo_dark</item>
      <item name="android:minHeight">@dimen/calc_btn_h</item>
      <item name="android:minWidth">@dimen/calc_btn_w</item>
      <item name="android:textColor">#ffffff</item>
</style>

to a button dynamically you need to use both setBackgroundResource() and setTextAppearance() functions. E.g.:

btn.setBackgroundResource(R.drawable.btn_default_holo_dark);
btn.setTextAppearance(context, R.style.ButtonHOLO);

where

btn_default_holo_dark

is a name of .xml file which describes a selector for your button.


The easiest way I found to circumvent this obvious flaw was to make two buttons. Make one of them Visibility.gone. Then simply change Visibility from the other one to gone and activate the first one by Visibility.visible.

I don't really like that solution, but it's faster and saner than the alternatives I found so far.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜