Streetboy
Streetboy

Reputation: 4401

How to change button text color programmatically on press?

I create button like this:

Button button = new Button(this); 
button.setText("2012");
button.setBackgroundColor(Color.TRANSPARENT);
button.setOnClickListener(mCorkyListener);
layout.addView(dateButton);

On click listiner i have this method. Here i want to change button text color. Bu View don't have this method

    private OnClickListener mCorkyListener = new OnClickListener() {
        public void onClick(View v) {
          // do something when the button is clicked
            //v.setBackgroundColor(Color.RED);
//so how to change pressed button text color ?
//v.setTextColor(colors);
        }
    };

There wouldn't be just one button. There would be many of those and i need to chnage text color when button pressed.

Upvotes: 0

Views: 5178

Answers (5)

Barak
Barak

Reputation: 16393

I know you asked about changing text color, and everyone else has pretty well covered that, but you could also change the button color itself (which I find much more visible than a text color change :p)...

import android.graphics.PorterDuff;

To set it to green (assuming you start with a standard gray button):

aButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        Button aButton = (Button) view.findViewById(R.id.abutton);
        aButton.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
    }
}

Upvotes: 1

Lalit Poptani
Lalit Poptani

Reputation: 67286

If you are interested to use the View of onClick(View v) then just cast it to Button

     public void onClick(View v) {
        if(v instanceof Button){
              ((Button)v).setTextColor(Color.WHITE);
           }
     }

Upvotes: 0

user370305
user370305

Reputation: 109237

 private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {          
     Button button = (Button)v;
     button.setTextColor(Color.RED);
        }
    };

Upvotes: 0

thepoosh
thepoosh

Reputation: 12587

the best way to do this is not programmatically (using selector), but if you want to do it programmatically you can cast it to Button and then change the color.

public void onClick(View v) {
    Button b = (Button) findViewById(v.getId());
    b.setBackgroundColor(Color.RED)l
}

Upvotes: 0

Sreedev
Sreedev

Reputation: 6653

button.setTextColor(Color.WHITE);

This will change the textcolor of the button.Do u want to give a press effet to button when click on it?

Upvotes: 0

Related Questions