简体   繁体   中英

How to change style attribute value in programmatically?

I have button and I set style from xml now on click of button I want to change style like

style="@style/ButtonNotSelected"

Place to

style="@style/ButtonSelected"

programmatically..

Please help..!!!

It will better if you use xml and a selector , to get your button change color when it is pressed, you could define an XML file called res/drawable/my_button.xml .

Set my_button.xml as background to your button.

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/button_pressed" />
  <item
    android:state_pressed="false"
    android:drawable="@drawable/button_normal" />
</selector>

@drawable/button_pressed something like this :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape>
            <solid android:color="#449def"/>
            <stroke android:width="1dp" android:color="#2f6699"/>
            <corners android:radius="3dp"/>
            <padding android:left="10dp" android:top="10dp" android:right="10dp"
                     android:bottom="10dp"/>
        </shape>
    </item>
</selector>

@drawable/button_normal something like this :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item>
        <shape>
            <gradient android:startColor="#449def" android:endColor="#2f6699" android:angle="270"/>
            <stroke android:width="1dp" android:color="#2f6699"/>
            <corners android:radius="4dp"/>
            <padding android:left="10dp" android:top="10dp" android:right="10dp"
                     android:bottom="10dp"/>
        </shape>
    </item>

</selector>

try like this:

 ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
 Button button = new Button(newContext);

OR

 btn.setBackgroundResource(R.drawable.back_button_answer);
 \res\drawable\back_button_answer.xml
<?xml version="1.0" encoding="utf-8"?>
 <shape xmlns:android="http://schemas.android.com/apk/res/android" 
 android:shape="rectangle" >
 <corners android:radius="10dip" />
 <!-- background -->

   <gradient
            android:startColor="#D6D7D6"
            android:centerColor="#E2E2E2"
            android:centerY="0.75"
            android:endColor="#D6D7D6"
            android:angle="270"
    />

   <stroke android:width="2dip" android:color="#fff"/>
   </shape>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM