replace selector images dynamically android

October 13, 2012 | Rishabh Agrawal | General

Android lets you  change the button’s image at runtime depending on it’s states like s focused or pressed.

This is achieved using selectors .The selector  xml is created in drawable folder ,which is a sub folder of res folder. In this example when the button is pressed the background image changes.

The selector.xml is given bellow

<?xml version=”1.0″ encoding=”utf-8″?>

<selector xmlns:android=”http://schemas.android.com/apk/res/android” >

<item android:drawable=”@drawable/ok_pressed”

android:state_pressed=”true” />

<item android:drawable=”@drawable/ok”  />

</selector>

 

Code in layout  file :

Here, we set selector as the background of the button

<Button

android:id=“@+id/b1”

android:layout_width=“wrap_content”

android:layout_height=“wrap_content”

android:background=“@drawable/selector”

android:text=“1”

/>

Also, we can dynamically replace selector images  in the following manner.

StateListDrawable -Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string ID value.

 

Button button=(button) findViewById(R.id.button_id);

StateListDrawable state = new StateListDrawable();

state = new StateListDrawable();

//add new image resource for a specific state

state.addState(new int[] {android.R.attr.state_pressed},

getResources().getDrawable(R.drawable.btn_up_cyan));

state.addState(new int[] {android.R.attr.state_focused},

getResources().getDrawable(R.drawable.btn_up_cyan));

button.setBackgroundDrawable(state);//set the background of button according to ‘state’

 

 

Hope this post is helpful . 🙂


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal