Programmatically change button background drawable onClick - android

I am trying to toggle my button's background drawables, so that when the user clicks the button its background is changed and when the user clicks the button again its background returns to defaul. Here is my code:
public void Favorites(View V) {
Button star = (Button) findViewById(R.id.buttonStar);
if(star.getBackground().equals(R.drawable.btn_star_off)) {
star.setBackgroundResource(R.drawable.btn_star_on);
} else {
star.setBackgroundResource(R.drawable.btn_star_off);
}
}
I am pretty sure this is not how you use drawables with if statements. Can someone suggest a way to do it?

private boolean isButtonClicked = false; // You should add a boolean flag to record the button on/off state
protected void onCreate(Bundle savedInstanceState) {
......
Button star = (Button) findViewById(R.id.buttonStar);
star.setOnClickListener(new OnClickListener() { // Then you should add add click listener for your button.
#Override
public void onClick(View v) {
if (v.getId() == R.id.buttonStar) {
isButtonClicked = !isButtonClicked; // toggle the boolean flag
v.setBackgroundResource(isButtonClicked ? R.drawable.btn_star_on : R.drawable.btn_star_off);
}
}
});
}

You can create an xml in the drawable folder.
This xml (you choose the name...let's call it "bg_button_star.xml") could look just like this:
<?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/btn_star_on" />
<item android:drawable="#drawable/btn_star_off" />
Then you have to assign this drawable file to the Button background property in the layout file.
android:background="#drawable/bg_button_star"
If you want to do this programmatically then you just have to do:
button.setBackgroundResource(R.drawable.bg_button_star);
When the user click the first time on the button, you set the Selected state to 'true'. The background changes accordingly. (viceversa for the 'false' Selected state).

You can do in your onClick() something like:
if(star.getTag()==R.drawable.btn_star_on){
star.setTag(R.drawable.btn_star_off);
star.setBackgroundResource(R.drawable.btn_star_off);
} else {
star.setTag(R.drawable.btn_star_on);
star.setBackgroundResource(R.drawable.btn_star_on);
}
Obviously it's better to the the tag before the if and else statement based on your informations. I don't know the rest of your code and how you check if this button has to be iniziatilized with the drawable resource btn_star_off or btn_star_on

You can try this.
public void Favorites(View V) {
Button star = (Button) findViewById(R.id.buttonStar);
if(star.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.btn_star_off).getConstantState()))
{
star.setBackground(R.drawable.btn_star_on);
} else {
star.setBackground(R.drawable.btn_star_off);
}
}
But make sure you are calling this method onClick() of the start button.
Other wise you have to do something like this.
Button star = (Button) findViewById(R.id.buttonStar);
star.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.getBackground().getConstantState().equals(getResources().getDrawable(R.drawable.btn_star_off).getConstantState()))
{
v.setBackground(R.drawable.btn_star_on);
} else {
v.setBackground(R.drawable.btn_star_off);
}
}
});

In this case, instead of using Button you should use ToggleButton.
There is a API Guide for it:
http://developer.android.com/guide/topics/ui/controls/togglebutton.html

Dont do it like that. Use a selector resource instead http://www.compiletimeerror.com/2014/03/android-button-selector-tutorial-with.html

Related

Android Studio - Change image when in different state

I want to have a favorite button on my app like in Gmail
So, when the user click on the star, the star became yellow, and when the user clicked it again, it turn back to normal
How can i make this happen with my custom image?
i have two images
when its not favorited (heart-grey.png)
and when its favorited (heart-red.png)
You can use visibilty to do this.You have to define the xml to have both images at the same postion(It can be done using Relative layout).
final ImageView play = (ImageView) findViewById(R.id.play);
final ImageView play2 = (ImageView) findViewById(R.id.play2);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Drawable playImage = play.getDrawable();
if (playImage.isVisible()){
play.setVisibility(View.GONE);
play2.setVisibility(View.VISIBLE);
mediaPlayer.start(); }
}
});
play2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Drawable playImage2 = play2.getDrawable();
if (playImage2.isVisible()){
play2.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
mediaPlayer.pause();
}
If your star is an ImageButton you can do something like this :
starSelected.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add a condition to detect if it is already a favorite or not
if(starSelected.getDrawable() == R.drawable.theimage2) {
starSelected.setImageResource(R.drawable.thenewimage);
}else{
starSelected.setImageResource(R.drawable.thenewimage2);
}
}
});
Hope it helps
In your java code create a boolean flag:
boolean isSelected = false
Set an onClickListener inside your onCreate for the star (ImageView, Button whatever it is). Inside onClick, check for the flag like this:
if (isSelected) {
// change image src to unselected
isSelected = false;
} else {
// change image src to selected
isSelected = true;
}
and also you can save the boolean state with SharedPreferences to make sure you get the correct state every time.

How to change background of button on tap?

I am having a button I want to do toggle on button like on and off,What I required is I am having two backgroundimages.
When I first time tap on button first background image should be done and on second time second background image should be changed like in toggle button.
Anybody please help me as I am new to android.
This is my activity:
public class MainActivity extends Activity {
private Button Button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button1 = (Button) findViewById(R.id.Button1);
Button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setBackgroundResource(R.drawable.ic_launcher);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Thanks.
Create a xml file in the drawable with the following code and change the background of the button to this drawable
customButton.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="false" android:drawable="#drawable/image_not_pressed"> </item>
<item android:state_pressed="true" android:drawable="#drawable/image_pressed"></item>
</selector>
Then add background to the image
<ImageView
android:layoutWidth="wrap_content"
android:layoutWidth="wrap_content"
android:background="#drawable/customButtom" />
You can use setTag to do that.
First>
Button1.setTag("ON");
and secondly in your onclicklistener add this:
if (v.getTag().toString().equals("ON")) {
v.setTag("OFF");
v.setBackgroundResource(R.drawable.ic_launcher);
}else {
v.setTag("ON");
v.setBackgroundResource(R.drawable.ic_launcher2);
}
Use ImageButton instead of Button,change image on the surface of the ImageButton by the setImageResource(int) method.
You can maintain the setSelected state for the Button and change the image by checking if it isSelected on Button click
Try using
Button button = new Button(this);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
if (v.isSelected())
{
v.setSelected(false);
}
else
{
v.setSelected(true);
}
}
});
Let me know if this works.

How to hide one item(Button) and show another item(Button) from menu (Buttons in ActionBar) in single Activity

As attached in screenshot when I click on edit button then i want to hide edit button and show save button. How can i do that?
My menu file is as below:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/edit_button"
android:icon="#drawable/edit_button"
android:orderInCategory="100"
android:showAsAction="always"
android:title="#string/edit"/>
</menu>
Is it possible this with image as edit to another image as save when button is clicked once and as save to edit when button is clicked again.
Try this
#Override
public boolean onOptionsItemSelected(MenuItem item){
{
if(editing){
item.setIcon(R.drawable.ic_save);
}else{
item.setIcon(R.drawable.ic_edit);
}
return super.onOptionsItemSelected(menu);
}
final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
final Button btn2 = (Button) findViewById(R.id.btnDate2);
dp2.setVisibility(View.GONE);
or
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
or
btn2.setVisibility(View.INVISIBLE);
when need visible:
btn2.setVisibility(View.VISIBLE);
or you use Invisible or Gone, but not both!
Based on your comments, you need other than asked.
Make not relevant, but change the
<item
android:id="#+id/edit_button"
to
<item
android:id="#+id/edit_or_save_button"
From the name you should know what will be the next:
if you press the button when it was an Edit, than you will do stuff in the activity which allows editing your data, but this button will change his text ( and action) to Save!
Of course you will assign different action listener, which will do the validation and save action.
If you really want to stick with 2 button idea (highly disagree with that) :
Button edit_button = (Button)findViewById(R.id.edit_button);
Button save_button = (Button)findViewById(R.id.save_button);
...
edit_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
edit_button.setVisibility(View.INVISIBLE);
save_button.setVisibility(View.INVISIBLE);
DoEdit(v);
}
});
save_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
save_button.setVisibility(View.INVISIBLE);
edit_button.setVisibility(View.INVISIBLE);
DoValidationAndSave(v);
}
});
I hope it solve your problem!
Try this,
public boolean checkHide = false
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
case EDIT:
if(checkHide){
checkHide=false;
item.setTitle("edit");
// ToDo your function
}
else{
checkHide=true;
item.setTitle("save");
// ToDo your function
}
}

How to make a view visible when a button is clicked and make that view invisible when the button is again clicked?

I have a layout which is invisible when the activity starts.When I click on a button the layout becomes visible.My requirement is when I click the button for the second time, the layout should be invisible.I know this is a silly question but as I am a new to android, I am unable to figure it out.
Try the following code to toggle the visibility of the view:
v.setVisibility(v.getVisibility() == View.INVISIBLE ? View.VISIBLE
: View.INVISIBLE);
You can also implement by using boolean FLAG.
e.g. Declare
boolean visibility_Flag = false;
button..setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(visibility_Flag){
YourView.setVisibility(View.INVISIBLE);
visibility_Flag = false;
} else {
YourView.setVisibility(View.VISIBLE);
visibility_Flag =true;
}
}
});

Button click to change background image of clicked button

I am trying to change the background image of a button that is clicked. The button whose image I am trying to toggle is the same button that is clicked. I ultimately want the program to test the current background image and change it to the other picture given the result of the test.
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (testButton.equals(getResources().getDrawable(R.drawable.fakepicture))) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
}
}//end void onClick
});//end test button on click listener
try
testButton.getBackground().equals(getResources().getDrawable(R.drawable.fakepicture));
However ToggleButton might suit your case better.
As others have said, your equals method is comparing the button itself with the image, but you need to compare the background drawables.
I recommend loading the images drawables you want to use and then using their references later to make things more clear, something like this:
final Drawable first = getResources().getDrawable(
android.R.drawable.arrow_up_float);
final Drawable second = getResources().getDrawable(
android.R.drawable.arrow_down_float);
final Button testButton = (Button) findViewById(R.id.toggleButton);
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (testButton.getBackground().equals(first)) {
testButton.setBackgroundDrawable(second);
} else {
testButton.setBackgroundDrawable(first);
}
}
});
as the other friends answered , it is preferable to use the ToggleButton in Android ,
and in your case, if you want to keep your code , so your method should be like this :
final Button testButton = (Button) findViewById(R.id.buttonTestButton);
int status = 0;//GLOBAL VARIABLE : the status of the Button ( 0 or 1 )
testButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//toggle picture
if (status == 0) {
testButton.setBackgroundResource(R.drawable.alternatepicture);
status=1 ; // change the status to 1 so the at the second clic , the else will be executed
}
else {
testButton.setBackgroundResource(R.drawable.fakpicture);
status =0;//change the status to 0 so the at the second clic , the if will be executed
}
}//end void onClick
});//end test button on click listener
You can simply use ToggleButton: Android ToggleButton and use StateList for the changing of the background: StateList using the check attribute.
You can use Buttons or Image buttons..
private ImageButton mod1,mod2;
mod1 = (ImageButton) findViewById(R.id.mod1);
mod2 = (ImageButton) findViewById(R.id.mod2);
mod1.setOnClickListener(this);
mod2.setOnClickListener(this);
public void onClick(View v) {
mod1.getDrawable().clearColorFilter();
mod2.getDrawable().clearColorFilter();
switch (v.getId()) {
case R.id.mod1:
mod1.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
case R.id.mod2:
mod2.getDrawable().setColorFilter(0xfff47521,PorterDuff.Mode.SRC_ATOP);
break;
}
}

Categories

Resources