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
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.
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.
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 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.