Change button states programmatically.

by / Monday, 05 August 2013 / Published in Android

A button consists of text or an icon (or both text and an icon) that communicates what action occurs when the user touches it.

A Button widget can exist in one of several different states (pressed, focused, or niether) and, using a state list drawable,  different background image can be provided for each state.

Here is a code that represents the change of states of a button (state_pressed,state_focused).

Code  for layout:

<Button
android:id="@+id/btn_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:background="@drawable/home_button"/>

Code for drawable:

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

<item android:state_pressed="true"
android:drawable="@drawable/home_s_focused" /> <!-- pressed -->
<item android:state_focused="true"
android:drawable="@drawable/home_s_focused" /> <!-- focused -->

<item android:drawable="@drawable/home_btn" /> <!-- default -->
</selector>

code for Activity:

MainActivity extends Activity implements OnClickListener

Button home;

home=(Button)findViewById(R.id .btn_home);//initialization

home.setOnClickListener(this);

public void onClick(View v) {
Button btn=(Button)v;
switch (btn.getId()) {
case R.id.btn_home:

btn.setSelected(true);//home button is selected
view.setSelected(false);
save.setSelected(false);

 

TOP