How to change background of button on tap? - android

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.

Related

ImageButton Won't Change 'background' When Pressed and Released

I'm making an app that has buttons and when a button is clicked, it will play a sound. My problem is that I couldn't find a way to change mSoundButton's background when pressed and released. I'm using 'background' instead of 'src' so I can shrink the button without cutting from edges. I haven't added sounds yet because I want to solve this issue before starting to add sounds.
Here is my codes for the button in MainActivity.java (It works okay, but not in the way I wanted. It changes background when pressed but not released.)
final ImageButton mSoundBtn;
final boolean[] soundBtnClicked = {false};
mSoundBtn = findViewById(R.id.soundButton);
mSoundBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(soundBtnClicked[0])
mSoundBtn.setBackgroundResource(R.drawable.button_clicked);
else
mSoundBtn.setBackgroundResource(R.drawable.button_not_clicked);
soundBtnClicked[0] = !soundBtnClicked[0];
}
});
and here is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/soundButton"
android:layout_width="match_parent"
android:layout_height="70dp"
android:background="#drawable/button_not_clicked"
android:contentDescription="TODO" />
</LinearLayout>
UPDATE (PROBLEM SOLVED):
I wanted the mSoundBtn to change image when pressed, then change image again when it is released. I used the Handler class and the postDelayed() method to create a delay between two image changes. It doesn't actually wait for user to release the button but still solved my issue. Following is the solution I found:
public ImageButton mSoundBtn;
Handler h = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSoundBtn = findViewById(R.id.soundButton);
mSoundBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSoundBtn.setBackgroundResource(R.drawable.button_clicked);
h.postDelayed(new Runnable() {
public void run() {
mSoundBtn.setBackgroundResource(R.drawable.button_not_clicked);
}
}, 1000); // 1 Second
}
});
What happens is when the mSoundBtn is clicked, It changes image and waits for 1000 milliseconds (1 second), then changes back to previous image which creates some kind of animation when it is pressed so the user can understand when the button is pressed.
Thanks for anyone who have tried to help, thanks for reading. :)
You shouldn't define it as 'final'
Sample:
public class SampleActivity extends AppCompatActivity {
//Variables
public ImageButton mSoundBtn;
public boolean isSoundBtnSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
mSoundBtn = findViewById(R.id.soundButton);
mSoundBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!isSoundBtnSelected)
mSoundBtn.setBackgroundResource(R.drawable.button_clicked);
else
mSoundBtn.setBackgroundResource(R.drawable.button_not_clicked);
isSoundBtnSelected = !isSoundBtnSelected;
}
});
}
}
If I understand you correctly, you want an action to be done after the user removed the finger from the button (meaning the press is done).
Try using OnTouchListener instead of OnClickListener:
imageButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_UP)
{
// change background and other stuff...
return true;
}
return false;
}
});
If you only wanted to change the button's background when it pressed, you can use a selector drawable for that, like so:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#color/black" /> <!-- pressed -->
<item android:state_activated="true"
android:drawable="#color/colorAccent" /> <!-- focused -->
<item android:drawable="#color/colorPrimary" /> <!-- default -->
and just place it as the button's background.
Another option is to use a toggle button and OnChecked listener and change the background when the user checks (press) the button. If you want the background to be permanently changed after the first toggle you can implement this by changing the background only after the first toggle.

How to switch background of button in RecyclerViewAdapter

I have buttons in my Recyclerview what is want to do is whenever user clicks first button the background of that button should changed and when user clicks next button that time first button should appear as normal button. how to do it? Please help me.
Here is my sample code:
#Override
public void onBindViewHolder(final AreaRecyclerViewAdapter.ViewHolder Viewholder, final int position) {
final GetAreaAdapter getAreaAdapter1 = getAreaAdapter.get(position);
Viewholder.btn_name.setText(getAreaAdapter1.getBtn_name());
setImageIntoButton( Viewholder.btn_name,getAreaAdapter1.isSelected());
Viewholder.btn_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getAreaAdapter1.setSelected(!getAreaAdapter1.isSelected());
setImageIntoButton(Viewholder.btn_name,getAreaAdapter1.isSelected());
Viewholder.btn_name.setBackgroundResource(R.drawable.ripple_effect);
}
});
}
private void setImageIntoButton(Button buttonView,boolean isSelected){
if(isSelected)
buttonView.setBackgroundResource(R.drawable.ripple_effect);
else
buttonView.setBackgroundResource(R.drawable.button_2);
}
Use State-List drawables
create a xml file in your drawable directory
and add something like
button_bg.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/some_drawable_for_pressed_state"
android:state_pressed="true"/>
<item android:drawable="#drawable/default_drawable"/>
</selector>
and set it as background for the button.
android:background="#drawable/button_bg.xml".

Programmatically change button background drawable onClick

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

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 change the image of a button with every click?

I created a button in the layout . In the Drawable folder I created a XML file named btn01_state. The btn01_state.xml is assigned to the button i created through "android:background=#drawable/btn01_state"
Now, the button has a default image img1.when i click on the button, the image1 changes to img2, and once i release the clicked mouse button, the image2 again changed to img1 again.
what i want to do is,to change the image of the button with evey click.
for an example, initially
btn01 has img01
if btn01 is pressed==> set img of btn01 to img02 and keep img02 till the btn01 is pressed again. Now, btn01 has img02 on it.
When btn01 is pressed, set img01 to btn01.
I hope this clarified more what i want to do.
btn_selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/android_blue"
android:state_pressed="true" />
<item android:drawable="#drawable/ic_launcher"
android:state_focused="true" />
<item android:drawable="#drawable/ic_launcher" />
main.xml
<Button
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/btn01"
android:background="#drawable/btn01_state"/>
You can do it easily within the code.
boolean isPressed = false;
button.setOnClickListener(buttonListener);
OnClickListener buttonListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(isPressed)
button.setBackgroundResource(R.drawable.icon1);
else
button.setBackgroundResource(R.drawable.icon2);
isPressed = !isPressed;
}
};
Simple way
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
btn.setBackgroundDrawable(getResources().getDrawable(R.drawable.locationbutton_on));
}
});
Make it in code perhaps. Put a listener on the button and when the button is clicked the background is changed.

Categories

Resources