2

I'm new to android programming and would like to extend a button class so that I can add a custom field to the button, and then change the way the button is displayed dependent on the field. I've done a few tutorials, had a good bash around and have something that compiles, but doesn't work - so I'm looking for tips on where I have gone wrong.

What I'd like to achieve is more complex than my example, but once I can get this example to work I think I would have a good crack at getting the rest up and going.

For my example, I'd like a button that has a isRed boolean member/attribute. If the member is set, then we change a drawable rectangle on the button to a red colour, if it is false, then the drawable is green.

To do this I have:

  • created a redbutton.xml file in my res/drawable directory. This file consists of a selector that provides either red or green rectangle, dependent on the isRed state.
  • created a RedButton.java file in my src/com.example.redbutton directory. This file contains a RedButton class that extends Button
  • created a attrs.xml file in my res/values directory. This lists the isRed member/attributes
  • put two buttons in my main layout. One button has custom:isRed set to true, the other has isRed set to false.

In theory I should then have two buttons in my app, one red, one green. Unfortunately I have two green buttons! I cannot seem to get the

<item custom:isRed="true"> 

in redbutton.xlm to evaluate to true. However, If I change this line to be

<item android:state_pressed="true">

then i have a red button whenever I press the button. To me the problem seems to be that accessing my custom field always evaluates to false!

Below is the code that I have written. Can anyone give me some tips on what I have done wrong?

redbutton.xml

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

<!-- if the isred value is true, then make the background red -->
<!--    <item android:state_pressed="true"> --> 
     <item custom:isred="true" >  
             <shape android:shape="rectangle"  >
             <size android:width="100dp"
                android:height="100dp"/>
             <solid  android:color="#ff0000"/>             
         </shape>
     </item>
<!-- otherwise make it green -->
    <item >
        <shape android:shape="rectangle"  >
             <size android:width="100dp"
                android:height="100dp"/>
            <solid  android:color="#00ff00"/>       
         </shape>
     </item>
</selector>  

RedButton.java

package com.example.redbutton;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.Button;

public class RedButton extends Button
{

    private boolean mIsRed;

    public RedButton (Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.getTheme().obtainStyledAttributes(
                attrs,
                R.styleable.RedButton,
                0, 0);

           try {
               mIsRed = a.getBoolean(R.styleable.RedButton_isred, false);
           } finally {
               a.recycle();
           }
    }


    //sets and gets for members
    public boolean getIsRed() 
    {
        return mIsRed;
    }

    public void setIsRed(boolean isRed) 
    {
        mIsRed =  isRed;
    }
}

attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="RedButton">
        <attr name="isred" format="boolean" />
    </declare-styleable>
</resources> 

fragment_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.example.redbutton"
    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.redbutton.MainActivity$PlaceholderFragment" >

    <com.example.redbutton.RedButton 
                android:id="@+id/Button1"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="RedButton"
                android:textSize="30sp" 
                custom:isred="true" 
                android:drawableBottom="@drawable/redbutton"              
    />
    <com.example.redbutton.RedButton 

                android:id="@+id/Button2"
                android:layout_width="0dp"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="GreenButton"
                android:textSize="30sp" 
                custom:isred="false"              
                android:drawableBottom="@drawable/redbutton"
    />
</LinearLayout>
1

2 Answers 2

4

You question is quite unclear. The most that I could do now is just guess what you want to achieve.

Do you want to have a button that has a default color when it is not pressed yet, and then changes to red or green? If so, then here's a sample app for you.

The app has 3 buttons: one named Red, one named Green, and one named switch. Press Red and Green to see the background change from default to the selected color. If you press switch, the button will change into the opposite color (from green to red; or red to green)

package com.example.buttontest;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;

public class ColoredButton extends Button {

    private boolean isRed = true;

    public ColoredButton(Context context) {
        super(context);
    }

    public ColoredButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ColoredButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void setIsRed(boolean isRed) {
        this.isRed = isRed;
        changeBgColor();
    }

    private void changeBgColor() {
        setBackgroundResource(isRed ? R.drawable.bg_red : R.drawable.bg_green);
        setText(isRed? "Red" : "Green");
    }

}

the main.xml file: notice that the xml tag for the red and green buttons reference to the ColoredButton class. That's because you're going to get a ClassCastException if you try to use the generic Button class. refer to this for more info.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.buttontest.MainActivity" >

    <com.example.buttontest.ColoredButton
        android:id="@+id/btnRed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Red" />

    <com.example.buttontest.ColoredButton
        android:id="@+id/btnGreen"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Green" />

    <Button
        android:id="@+id/btnSwitch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Switch Color" />

</LinearLayout>

Now you have to create two separate drawable xml files. As Christopher said, you can't just create xml tags on your own. Android does not recognize them.

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

    <item android:state_pressed="true"><color android:color="#00ff00" />
    </item>
    <item android:drawable="@android:drawable/btn_default"></item>

</selector>

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

    <item android:state_pressed="true"><color android:color="#ff0000" />
    </item>
    <item android:drawable="@android:drawable/btn_default"></item>

</selector>

The main activity:

package com.example.buttontest;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    ColoredButton btnRed;
    ColoredButton btnGreen;
    Button btnSwitch;

    boolean switched = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initButtons();
    }

    private void initButtons() {
        btnRed = (ColoredButton) findViewById(R.id.btnRed);
        btnGreen = (ColoredButton) findViewById(R.id.btnGreen);

        btnRed.setIsRed(true);
        btnGreen.setIsRed(false);

        btnSwitch = (Button) findViewById(R.id.btnSwitch);
        btnSwitch.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        btnRed.setIsRed(switched);
        btnGreen.setIsRed(!switched);

        switched = !switched;
    }
}

Try the code and see if that's what you want.

1
  • Thanks for the tips. Your sample code was very helpful and it helped me to realise that i can't achieve what i want using xml, i need to write it in java. I've now written a solution to my problem. Thanks again, much appreciated Sep 24, 2014 at 0:28
0

I have a few design concerns with what you are trying to accomplish. First, why would you make a RedButton class, that clearly states it's a red button, and then allow it to not only not be red, but be green? Why not have a RedButton and a GreenButton? Much less confusion, and clearer purpose.

Second, selectors work off of button states defined by the Android framework. You can't inject your own custom type in there and expect it to know what you're talking about. You can surely set the background to the appropriate color in your custom Button constructor, and also change it appropriately in your setter, but I advise against that.

3
  • Thanks Christopher, Yes - you are correct having a red button that can be red or green is confusing - I should have written it as a red_green button. I have really only written this example as a simple way to show my problem. The problem is that i am trying to have a class that extends a button, that has a state that can be changed, and then change the way the button is displayed according to its state. But you might have the answer to my question. Can I use a selector with a custom field? if not, then what would i use instead? Aug 29, 2014 at 9:28
  • What is the "state" you are trying to represent? Aug 29, 2014 at 16:55
  • Thanks for the help and advice on selectors. I did find on the web some code that allows you to override the selectors class and add your own states, but I decided that it would be better to just create red button drawables, green buttons drawables, and switch the drawable using java, rather than xml. Thanks for the help, much appreciated. Sep 24, 2014 at 0:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.