Change source image for image view when pressed - android

I have a scroll view with lots of image buttons. I want to change the image for an image button when it's pressed. The thing is that I want the image to remain until another image button is pressed. That's why I couldn't use a selector. What is the best practice to achieve this?

You want to do this.
ImageButton Demo_button = (ImageButton)findViewById(R.id.firstimage);
// when you click this demo button
Demo_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Demo_button.setImageResource(R.drawable.secondimage);
}
}
Try this. (updated setset to set)

Better solution, use the following xml as source of the image:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_activated="true">
<bitmap android:src="#drawable/image_selected"/>
</item>
<item>
<bitmap android:src="#drawable/image_not_selected"/>
</item>
</selector>
#Override
public void onClick(View v) {
v.setActivated(!v.isActivated());
}

The shortest way to achieve it, using only XML (no Java code):
Save the following as drawable/image_pressable.xml next to the two images:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/image_pressed" android:state_pressed="true" />
<item android:drawable="#drawable/image_regular" />
</selector>
then reference it as:
<ImageView android:src="#drawable/image_pressable" />
Tip:
Using state_pressed instead of state_activated allows the image to be changed when pressing it with the fingers. state_activated could be useful, if you want to dynamically change the status of the ImageView, but not if you just want it to behave different when pressed, without any code involved. Which is exactly what it was asked in the question of this topic.

the OnTouchListener is much better for what you have to do:
myImageButton.setOnTouchListener(new OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN :
myImageButton.setImageResource(R.drawable.image_when_pressed);
break;
case MotionEvent.ACTION_UP :
myImageButton.setImageResource(R.drawable.image_when_released);
break;
}
return false;
}
});

try below code :-
boolean flag=false;
ImageButton btn = (ImageButton)findViewById(R.id.btn);
// when you click this demo button
btn .setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!flag) {
btn.setBackgroundResource(R.drawable.imageonpress);
flag=true;
}
else {
btn.setBackgroundResource(R.drawable.image);
flag=false;
}
}
}

don't forget to create the field "fun"
Try this for changing image.When imageview is pressed
Like_btn.setOnClickListener(new OnClickListener()
{
**private boolean fun = true;**
public void onClick(View v)
{
if(fun)
{
Like_btn.setImageResource(R.drawable.unlike);
fun=false;
}
else
{
fun=true;
Like_btn.setImageResource(R.drawable.like);
Toast.makeText(getApplicationContext(), "Changed", Toast.LENGTH_LONG).show();
}
}
});

What worked for me was:
I created a new drawable xml file, for eg, image_state.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<bitmap android:src="#drawable/image_pressed"/>
</item>
<item>
<bitmap android:src="#drawable/image"/>
</item>
</selector>
And in my layout file, I set the src of the imageView as:
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/image_state"/>

ImageButton Demo_button = (ImageButton)findViewById(R.id.firstimage);
ImageButton second_button = (ImageButton)findViewById(R.id.secondimage);
// when you click this demo button
Demo_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Demo_button.setImageResource(R.drawable.secondimage);
second_button.setImageResource(R.drawable.firstimage);
}
}
second_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Demo_button.setImageResource(R.drawable.firstimage);
second_button.setImageResource(R.drawable.secondimage);
}
}
I Hope u want to like that
Right???

float alpha_first = 0.2f;
float alpha_second = 1.0f;
AlphaAnimation alphadp = new AlphaAnimation(alpha_second, alpha_first);
switch (v.getId()) {
case R.id.disable_deactivate_pic:
ImageButton disable_button =(ImageButton)findViewById(R.id.disable_deactivate_pic);
if (!flag) {
disable_button.setImageResource(R.drawable.enable_active);
linearLayout_for_picture = (LinearLayout) findViewById(R.id.linearlayout_imageView_pic);
alphadp.setFillAfter(true);
linearLayout_for_picture.startAnimation(alphadp);
flag=true;
}
else {
disable_button.setImageResource(R.drawable.disable_active);
alphadp.setFillAfter(false);
linearLayout_for_picture.startAnimation(alphadp);
flag=false;
}
break;

You can use a StateListDrawable to achieve this. This method also works for ImageButtons. I prefer it to setting additional listeners.
I've also compiled a class of additional helpers: http://alexanderwong.me/post/40799636705/android-change-background-image-drawable-on-press
public static StateListDrawable makeStateDrawable(Drawable drawable, Drawable pressedDrawable, Drawable disabledDrawable) {
boolean set = false;
StateListDrawable stateDrawable = new StateListDrawable();
if (disabledDrawable != null) {
set = true;
stateDrawable.addState(new int[] { -android.R.attr.state_enabled }, disabledDrawable);
}
if (pressedDrawable != null) {
set = true;
stateDrawable.addState(new int[] { android.R.attr.state_pressed }, pressedDrawable);
}
if (drawable != null) {
set = true;
stateDrawable.addState(new int[0], drawable);
}
return set ? stateDrawable : null;
}

state_pressed or state_activated did not work for me.
However, I succeeded with state_enabled
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="true" android:drawable="#drawable/checkbox_on" />
<item android:state_enabled="false" android:drawable="#drawable/checkbox_off" />
</selector>
Your xml should declare it as src:
<ImageView
android:id="#+id/img_checkmark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/checkbox_selector_filter"/>
Then in code, ensure you enable or disable it based on event/state:
imageCheckBox.isEnabled = true
This was easiest and cleanest for me

if you have an ImageView orImageButton and want to change image of that when its pressed, you can refresh activity for any pressed:
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int isFavor = c.getInt(c.getColumnIndex("isFavor"));
if(isFavor == 1){
db.execSQL("update content set isFavor=0 where ID="+idxx+";");
fav.setImageResource(R.drawable.favnot_ic);
Toast.makeText(context.getApplicationContext(),"item cleaned",Toast.LENGTH_LONG).show();
activity.finish();
activity.overridePendingTransition(0, 0);
context.startActivity(activity.getIntent());
}
else{
db.execSQL("update content set isFavor=1 where ID=" + idxx + ";");
fav.setImageResource(R.drawable.fav_ic);
Toast.makeText(context.getApplicationContext(),"Item added...",Toast.LENGTH_LONG).show();
activity.finish();
activity.overridePendingTransition(0, 0);
context.startActivity(activity.getIntent());
}
}
});

If you save the selection on click and then reload the image scroll gallery (or scroll menu) and then reload and scroll to the selection with a replaced image, then you might be able to do it. As far as I know none of the inbuilt gallery or menu functions have the ability to replace images once they are loaded and displayed.

if u have already a button in ur app that will do the swap between the two pics u have when its clicked then there is a simple Code :D
// to add Images in android we simply " Copy them from their location and past in (res --> drawable)"
// then drag and drop "ImageView" and select the image u want to display
// u can adjust the scale throw "scaleType , layout_Width & layout_Height"
public boolean swap = true;
public void change(View view)
{
ImageView i = (ImageView) findViewById(R.id.img);
if (swap)
{
i.setImageResource(R.drawable.images);
swap=false;
}
else
{
swap=true;
i.setImageResource(R.drawable.couple);
}
}

Although it's too late to answer. But someones may get help from this answer.
It's working like charm -
circularImageView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
circularImageView.setImageResource(R.drawable.profile_edit_photo);
break;
case MotionEvent.ACTION_UP:
circularImageView.setImageResource(R.drawable.photo_male_8);
break;
case MotionEvent.ACTION_MOVE:
Log.i("ImageViewEvent", "Action_Move_Called");
break;
}
return true; // Note: This return value must need to be true if you want to call MotionEvent.ACTION_UP: action.
}
});

Demo_button.setImageResource(R.drawable.secondimage)
//Demo_button is your event holder (the button or imageview or bitmap file which contains the image) and secondimage is your image (drawable) file, without any complications.
This does the trick.

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.

change background image of imageview on onclick

I have imageview and i whant when user click this imageview the background of this changed this is my code
btnImage =(ImageView) findViewById(R.id.image_button);
btnImage.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
}
});
but i dont know how in onclick change this background image
Why you do not use Selctor for ImageView when clicked.
res/drawable/selector.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/your_iamge_pressed" android:state_pressed="true" />
<item android:drawable="#drawable/your_iamge_pressed"
android:state_focused="true"
android:state_enabled="true"
android:state_window_focused="true" />
<item android:drawable="#drawable/your_iamge_normal" />
here in you ImageView set the selector as background : android:background="#drawable/selector.xml"
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/selector.xml" />
OR USE TouchListener To implement such idea
when you touch(Action Down) set one image as background and when you release (Action Up) set another Image as background.
here is the code
buttonONE.setOnTouchListener(new View.OnTouchListener(){
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN) {
buttonONE.setBackground(R.drawable.round_button_focus);
} else if (event.getAction() == MotionEvent.ACTION_UP) {
buttonONE.setBackground(R.drawable.round_button_unfocused);
// *******start Intent here********
}
}
};
I'm agree with #sajidkhan answer but #zahra you are doing mistake to set the selector as background wrong.
here i will explain #sajidkhan's answer as i know he might be expected here an image.png etc not a selector.xml
buttonONE.setBackground(R.drawable.round_button_focus);
round_button_focus means round_button_focus.png etc,
in MotionEvent.ACTION_DOWN set one background and when you release the button set another background eg. MotionEvent.ACTION_UP
follow #sajidkhan suggestion his answer might deserve as accepted if you think this helped you.
Here is the code
btnImage =(ImageView) findViewById(R.id.image_button);
btnImage.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
btnImage.setBackgroundResource(R.drawable.ic_launcher);
//put your image in drawable folder and change ic_luncher by your image.
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
}
});
Intent i=new Intent(fierst.this,second.class);
startActivity(i);
by executing these two line it will move to second activity so you can't able to see the result for image changed or not. To see the proper output for image change make these lines as comment
Hope this will helpful .thanks

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

Android - How to get the image resource to use in if statement

So I set a onClick listener to my ImageView via the xml file. It's called changeImage(). In that, I want it to be so:
if(img.getImageResource == R.drawable.1){
img.setImageResource(R.drawable.2);
}else if(img.getImageResource == R.drawable.2){
img.setImageResource(R.drawable.1)
}
Only the problem is, there's no such thing as getImageResource. How do I do it?
EDIT:
public void changeImage(View v) {
ImageView img = (ImageView) v.findViewById(R.id.img);
Drawable drawable = img.getDrawable();
if(drawable == getResources().getDrawable(R.drawable.lightbulb_off)){
img.setImageResource(R.drawable.ic_launcher);
}else if(drawable == getResources().getDrawable(R.drawable.ic_launcher)){
img.setImageResource(R.drawable.lightbulb_off);
}
}
does not work. Why???????? :'(
As alanv states, using a selector would work, where you'd be able to check the selected state of the ImageView.
I'd recommended separating your business logic from the UI though; e.g. create a LightBulb class which has a state of ON or OFF. Instead of relying on the current state of the ImageView when toggling, you'd just check the state of your lightBulb:
private void toggleSwitch() {
lightBulb.toggleSwitch();
updateLightBulbImage();
}
private void updateLightBulbImage() {
if (lightBulb.isSwitchedOn()) {
img.setImageResource(R.drawable.switched_on);
} else {
img.setImageResource(R.drawable.switched_off);
}
}
Calling Resources.getDrawable() returns a unique object each time, so == comparison will never return true. Drawables also don't generally implement Object.equals() in a way that would solve your issue either.
Instead, consider using a selector drawable as your image and ImageView.setSelected(boolean) to toggle between states.
res/drawable/lightbulb.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/ic_launcher" />
<item android:drawable="#drawable/lightbulb_off" />
</selector>
res/layout/your_layout.xml:
<ImageView android:id="#+id/img" android:src="#drawable/lightbulb" />
In your code, toggle selection state.
public void changeImage(View v) {
ImageView img = (ImageView) v.findViewById(R.id.img);
img.setSelected(!myImageView.isSelected());
}

imageView not changed when clicked in android

i've made a simple custom checkbox program in android,in that i have tken two images for "difault" and "checked" state as per user action i want to change that images..i have tried the following code which is not working,
my code is:
final ImageView chekbx =(ImageView)dialog.findViewById(R.id.chk_login);
if(chekbx.isSelected()){
System.out.println("checkbox check");
chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
}else{
chekbx.setBackgroundResource(R.drawable.checkbox);
}
Use selector for this purpose .
This is your checkboc:
<CheckBox
android:id="#+id/remb_ckh_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="#drawable/check_box_selector" />
And its selector :
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="#drawable/checkbox_selected" />
<item android:state_checked="false" android:drawable="#drawable/checkbox_unselected" />
</selector>
Try to use this code:
EDITED
final ImageView chekbx =(ImageView)dialog.findViewById(R.id.chk_login);
boolean flag =false; //TAKE AS A PUBLIC VAR
chekbx.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(flag)
{
chekbx.setBackgroundResource(R.drawable.checkbox);
flag=false;
}
else
{
System.out.println("checkbox check");
chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
flag = true;
}
}
});
Hope this will help you.
Android already has CheckBox view, you don't need to build one yourself.
Checkbox API:
http://developer.android.com/reference/android/widget/CheckBox.html
This checkbox can also have custom images, using a selector:
How to change default images of CheckBox
void onClick Login(View v)
{
if(checkbx.isSelected(){
chekbx.setBackgroundResource(R.drawable.checkbox_ticked);
<Set your new database with login details and phone ID to remember>
//check your database for login details here with registered details
}
else{
chekbx.setBackgroundResource(R.drawable.checkbox);
//check your database for login details here with registered details
}
}
This logic should help you. Thanks.

Categories

Resources