Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom button colours for disabled and enabled

Tags:

android

layout

I have an android application that has a button which I want to have black text and background while it is disabled and then a green background with white writing when it is enabled.

Ive got the enabling and disabling working but if I change the colors the button stays the same regardless of its state.

I've read that I need to use a custom selector to set the colors manually and this is what I have got so far:

continuebutton.xml in res/drawable:(green is declared in /res/values/colors.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item 
android:state_enabled="false"
    android.textColor ="@android:color/black"
    android:drawable="@android:color/black" />
<item 
    android:state_enabled="true"
    android.textColor ="@android:color/white"
    android:drawable="@color/green" />

continuebutton in layout xml file:

 android:id="@+id/continueButton"
   android:layout_width="200dp"
    android:layout_height="55dp"  android:layout_gravity="center" android:paddingTop="10dp" android:textSize="18dp" 
    android:text="@string/continueButton" android:background="@drawable/continuebutton" />

I think I'm doing something wrong in the continuebutton.xml file but I'm not sure how to fix it.

Any help would be greatly appreciated!

Thanks

UPDATE:

I have the background changing color, the last problem is resolve is the text color which is staying black regardless of whether the button is disabled or enabled(should be white for enabled).

Do i need to make a new xml file in res/drawable for the text color?

Any ideas?

like image 757
Rob Avatar asked Nov 05 '22 02:11

Rob


1 Answers

Remove the attribute

android:src="@drawable/continuebutton"

and use

android:background="@drawable/continuebutton"

at runtime you can change the background image by

myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.myfirstbg));
myButton.setBackgroundDrawable(getApplicationContext().getResources().getDrawable(R.drawable.mysecondbg));

if you want to use background Color remove both properties`

android:src="@drawable/continuebutton"
android:background="@drawable/continuebutton"

and change background color by using this

myButton.setBackgroundColor(Color.BLUE);
myButton.setBackgroundColor(Color.GREEN);
like image 92
Ravi1187342 Avatar answered Nov 09 '22 05:11

Ravi1187342