How can I change a button style dynamically in And

2019-02-16 15:26发布

This question already has an answer here:

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>
        <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?

4条回答
混吃等死
3楼-- · 2019-02-16 15:57

The easiest way I found to circumvent this obvious flaw was to make to 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.

查看更多
欢心
4楼-- · 2019-02-16 16:04

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.

查看更多
我只想做你的唯一
5楼-- · 2019-02-16 16:16

You might also want to take a look at 9 patch images. These are very useful for adjusting the image size and text tied to your widget or button based on the current device running your application.

9 patch

9 patch draw tool

查看更多
登录 后发表回答