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());
}
Related
On Android, a Button changes its background color when pressed.
How can we tell a button that it is pressed (without firing the onClick-action), so that it changes color, without the user pressing it? (for example triggered by a swipe action)
It should change color briefly, and then change back.
There a quite a few questions concerning keeping the pressed state. This question asks, how to set the button_pressed state briefly, as if clicked, but without a real click.
Button.setPressed(true) has not given a color change, neither has Button.performClick().
First, create the effect when button is hovered, clicked etc in XML. Put this style in your drawable.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Pressed button -->
<item android:drawable="#color/dark_green"
android:state_focused="true"
android:state_pressed="false"
/>
<item android:drawable="#color/dark_green"
android:state_focused="true"
android:state_pressed="true"
/>
<item android:drawable="#color/dark_green"
android:state_focused="false"
android:state_pressed="true"/>
<!-- Normal button -->
<item android:drawable="#color/green"
android:state_focused="false"
android:state_pressed="false"/>
</selector>
Then in your XML, initiates the style by using:
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#drawable/the_style_in_drawable"
android:text="click"/>
By putting the style in your XML, you don't have to initiate the style when button on click. Android will detect the button state and do the work for you. Just remember to put the state in selector.
To change a button state without anything else is done via
btn1.getBackground().setState(new int[]{android.R.attr.state_pressed});
To reset to ordinary, you use
btn1.getBackground().setState(new int[]{android.R.attr.state_enabled});
A Button's states can be found out via
btn1.getBackground().getState();
which resturns an int[]. You can compare its values to android.R.attr to find out which states are set.
Example Code
private void simulateClick(final ImageButton button,
final long clickDuration) {
button.getBackground().setState(new int[]{android.R.attr.state_pressed});
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(clickDuration);
} catch ( InterruptedException e ) {
// not bad if interrupted: sleeps a bit faster (can happen?)
}
Count.this.runOnUiThread(new Runnable() {
public void run() {
button.getBackground().setState(new int[]{android.R.attr.state_enabled});
}
});
}}).start();
}
Explanation
Each View has a Drawable as background image. A Drawable can be of different subtypes, here it is a StateListDrawable, as defined per XML. (See #Lynx's answer as an example of a XML defined drawable).
This Drawable can be told which state it is to assume (via setState) and does the layout itself.
AsyncTask for button color change illusion:
private class ChangeButtonColorMomentarily extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
btn1.setBackgroundDrawable(new ColorDrawable(Color.rgb(50, 50, 50)));//pressed state
}
#Override
protected String doInBackground(String... params) {
try {
Thread.sleep(1000);
} catch (Exception e) {
}
return "";
}
#Override
protected void onPostExecute(String result) {
btn1.setBackgroundDrawable(new ColorDrawable(Color.rgb(200, 200, 200)));//normal state
}
}
Also take note that if your API 16 above use setBackground() instead.
For changing the color of button at that time, you can use setOnTouchListener as:
button.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN){
//Button Pressed
}
if(event.getAction() == MotionEvent.ACTION_UP){
//finger was lifted
}
return false;
}
});
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.
Some XML attributes of buttons (such as background, textColor, etc) can be defined with color or drawable state List like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:color="#ffff0000"/>
<item android:state_focused="true"
android:color="#ff0000ff"/>
<item android:state_enabled="true"
android:color="#ff00ffff"/>
<item android:color="#ff000000"/>
</selector>
When view state changes (pressed/unpressed, for example), corresponding color is changed automatically.
How can I prograqmmatically handle some kind of stateChangedEvent to perform more complicated layout change, than just changing a color (for example, change font size or set another text)?
For focus changes and touch events you can register listeners by setOnFocusChangeListener and setOnTouchListener. And changes about disabled/enabled states you can perform directly after changing your button state.
// use the selector method to pass your button and image
// you can use color also
b1=(Button)findViewById(R.id.button1);
// b2=(Button)findViewById(R.id.button2);
selector(b1, R.drawable.image_1_2, R.drawable.image_1);
// selector(b2, R.drawable.image_2_2, R.drawable.image_2);
}
public void selector(Button b,int pressed_image,int normal_image )
{
StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
getResources().getDrawable(pressed_image));
states.addState(new int[] { },
getResources().getDrawable(normal_image));
b.setBackgroundDrawable(states);
}
Just override View.setPressed:
#Override
public void setPressed(boolean pressed) {
super.setPressed(pressed);
...
}
Handler onTouch(View v, MotionEvent event) for specific views and perform actions in MotionEvent.DOWN / Up according to your requirement.
You have to take a reference to the View Object (button) via findViewById(<object_id>) and than use the appropriate methods from the API.
For example:
private Button aButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
aButton = (Button) findViewById(R.id.your_button_id);
//example 1
aButton.setVisibility(SomeExpressionEvaluation ? View.GONE : View.VISIBLE);
//example 2
if (SomeExpressionEvaluation) {
aButton.setText("Some Text");
}
and so on, just take a look at the API, especially inherited methods from the View class.
I must say you can use a (touch listner) this how u use a touch listner
image=(ImageView)findViewById(R.id.image);
find ur image first
Add a touch Listner to ur image
image.setOnTouchListener(image_onTouch);
//Add a touch method which is by name image_onTouch
OnTouchListener image_onTouch=new OnTouchListener(){
#Override
public boolean onTouch(View arg0,MotionEvent arg1){
int iAction=arg1.getAction();
if(iAction==0){
image.setImageResource(R.drawable.image1);
}
else{
image.setImageResource(R.drawable.image2);
}
return false;
}
};
// image 1 is ur image which u want 2 click and image 2 is the image when you touch that image you have to make an another image in which background color do u wanna show and use it in the code
I had also this kind of problem in past. I solved by putting this XML file in separate drawable folder in Res instaed of drawable-mdpi or else. And make sure that you have to give this Xml as your button's background.
I have an ImageButton which on click i show a dialog box where users can either take a photo from the camera or choose from the gallery. On selecting image from either sources i setBitmap for that ImageButton to the image selected like this
SelectedPhoto = BitmapFactory.decodeFile(selectedImagePath);
DisplayPhoto.setImageBitmap(SelectedPhoto);
Now when some one has already selected an image and click the image again i want to show a different dialog which contains a third option "Remove Photo".
What property of the image button should i check and against what ?
ImageButton in XML
<ImageButton
android:id="#+id/DisplayPhoto"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginRight="8dip"
android:background="#drawable/signup_photo_selector" android:scaleType="centerCrop" />
ImageButton Background XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/signup_form_photo_selected" android:state_pressed="true"/>
<item android:drawable="#drawable/signup_form_photo"/>
</selector>
Would imgButton.getDrawable() work, since it returns null if no drawable has been assigned to the imagebutton?
If not, or if you don't want to get the entire drawable just to see if it's there, you can use a tag. imgButton.setTag(object) lets you store any object within the imagebutton... every time you set its background, you can tag a value that identifies whether its background was set. You could even use different values to differentiate whether you set its background using a camera or from the gallery, if that's useful. When you want to see if the imagebutton has a background or not, use imgButton.getTag() to retrieve the object.
Edit. Here is how you would use setTag and getTag. I will use an Integer object as the ImageButton's tag, where a value of 0 indicates no background has been set and a value of 1 indicates a background has been set. You can use an enum or final variables if you want to make the code a bit clearer, but using an Integer will work as an example.
public class MainActivity extends Activity, implements OnClickListener {
private ImageButton imgButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgButton = (ImageButton)findViewById(R.id.imgID);
imgButton.setTag(new Integer(0)); // no background
...
}
public void onClick(View view) {
ImageButton ib = (ImageButton)view;
int hasBackground = ib.getTag().intValue();
if(hasBackground==0) {
// imagebutton does not have a background. do not include remove option
...
} else {
// imagebutton has a background. include remove option
}
}
}
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.