How to create a Button, that blinks after clicked? - android

So far I learned how animations work and how to set the background of a button according to its state as described here.
Well, I defined an animation:
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:interpolator="#android:anim/accelerate_interpolator"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="50"
android:repeatMode="reverse"
android:repeatCount="6"/>
I start the animation in the onClick(View v) method. The problem now is, that the actual click action gets processed before the animation finishes. I know I could use an AnimationListener, but this would not look very nice to me since I'd have to call the actual click processes within the AnimationListener then.
Does anyone know a more skilful way to let a button blink after it gets clicked?

You can use the Selector tag like Follows: Create a New xml file and place it in your drawable folder and name it as shadow_color.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="#drawable/ask_footer"/>
<item android:state_focused="false" android:state_pressed="true" android:drawable="#drawable/askfooter_hover" />
<item android:drawable="#drawable/ask_footer" />
</selector>
And then go to that xml in which your Button is declared: And write one attribute in Button
android:background="#drawable/shadow_color"
and you are done.
Mark the answer if you find it usefull..

Define the onclick for the button
button1.setOnClickListener(
new Button.OnClickListener() {
public void onClick (View v){ calcular(1,v); }
}
);
Make your button blink
This makes the images defined in the XML alternate between each other.
public void calcular(final int p,final View v){
MediaPlayer mp = MediaPlayer.create(this, R.raw.click);
mp.start();
//v.setBackgroundResource(R.drawable.dia1btn_stl2);
final TransitionDrawable transition1 =
(TransitionDrawable) v.getBackground();
Handler blinkHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
transition1.startTransition(70);
break;
case 1:
transition1.resetTransition();
break;
}
super.handleMessage(msg);
}
};
for (int i=0; i<6; i++)
{
Message msg = new Message();
if(i % 2 == 0){
msg.what = 0;
}
else{
msg.what=1;
}
blinkHandler.sendMessageDelayed(msg, i*100);
}
/*mCurrentSeries.clear();
if(calcularctrl == 0){
calcularctrl = 1;
dtdodo = new DownloadImageTask(this , p , codacaovalue);
dtdodo.execute("wwwkjhdijdh");
}*/
Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
public void run() {
//v.setBackgroundResource(R.drawable.dia1btn_stl2);
mCurrentSeries.clear();
if(calcularctrl == 0){
calcularctrl = 1;
dtdodo = new DownloadImageTask(outer() , p , codacaovalue);
dtdodo.execute("wwwkjhdijdh");
}
try {
this.finalize();
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public acoesdetalhes outer(){
return acoesdetalhes.this;
}
}, 1000);
}
The XML of the button background
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
<item android:drawable="#drawable/mes1btn_stl2" />
<item android:drawable="#drawable/mes1btn_prssd2" />
</transition>
This code provided in part by user Alin.

Related

Glow button on and off

I have two images which I want to fade between causing a glowing on and off effect. This should run all the time like an animation, not just when the button is pressed.
Here are the two images:
This was working well before but after some hardware/android OS updates my animation is really jumpy. Here is the Animation XML I was using:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="#drawable/bottom_bar_add_dark"/>
<item android:drawable="#drawable/bottom_bar_add" android:duration="500" />
</animation-list>
I have looked high and low and cannot find an answer to this.
Edit
Here is the code that creates the image view and sets all its resources:
public ImageView findDevicesButton(){
bottomButton = new ImageView(this);
int id = bottomButton.generateViewId();
bottomButton.setId(id);
if(currentapiVersion >= 11){
bottomButton.setImageResource(R.drawable.animationxmladddevice);
//Background image
bottomButton.setBackgroundResource(R.drawable.bottom_bar);
saveButtonAnimation = (AnimationDrawable)bottomButton.getDrawable();
saveButtonAnimation.setEnterFadeDuration(1000);
saveButtonAnimation.setExitFadeDuration(1000);
bottomButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
findDevicesAlertBuilder();
}
});
}else{
bottomButton.setImageResource(R.drawable.bottom_bar_add);
bottomButton.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
bottomButton.setBackgroundResource(R.drawable.bottom_bar);
bottomButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
findDevicesAlertBuilder();
}
});
}
return bottomButton;
}
This is the back background image:
All together it should look like this with the center button glowing:

How to change the background of only one button when clicked?

I am generating my buttons programmatically.I want to change the background of the clicked button to menuitemsactivity_button_backgrnd.
The default background of the buttons is popup. I have done the following coding but the problem is that when I click the first button it changes its background, then when I click the second button the second button changes its background but the first button has the same menuitemsactivity_button_backgrnd background.
What I want to do is change the background of only the clicked button i.e at a time only one button has menuitemsactivity_button_backgrnd background.
I am posting my codes please guide me step by step:
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(getOnClickDoSomething(tv1));
l1.addView(tv2);
private OnClickListener getOnClickDoSomething(final Button tv1) {
// TODO Auto-generated method stub
return new View.OnClickListener() {
public void onClick(View v) {
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.menuitemsactivity_button_backgrnd));
Toast.makeText(MenuItemsActivity.this, "clicked"+v.getId()+","+tv1.getId(), 1000)
.show();
}
};
}
menuitemsactivity_button_backgrnd
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/blue_tab"
/>
</selector>
try doing something like this :
"<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
android:drawable="#drawable/blue_tab"
/>
<item android:state_pressed="false"
android:drawable="#drawable/whatever_the_unselected_drawable_is"
/>
</selector>"

How to replay a one shot animation

I want to make a one shot animation but be able to play it as many times as I want. Right now it plays only the first time.
.xml:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/p1_ch1" android:oneshot="true">
<item
android:drawable="#drawable/p1_ch1_5"
android:duration="500"/>
<item
android:drawable="#drawable/p1_ch1_4"
android:duration="1000"/>
<item
android:drawable="#drawable/p1_ch1_5"
android:duration="500"/>
</animation-list>
.java:
public void handler_p1_ch1_5 (View target){
ImageView iv = (ImageView)findViewById(R.id.p1_ch1_5);
AnimationDrawable aw = (AnimationDrawable)iv.getBackground();
aw.start();
}
Just call aw.stop() before aw.start()
Use this:
frameAnimation.setOneShot(true);
Change
android:oneShot="true" to
android:oneShot="false"
If you want to replay a one shot animation after previous animation finish you can do like
final AnimationDrawable animationDrawable = (AnimationDrawable) image.getDrawable();
if (!animationDrawable.isRunning()) {
int totalFrameDuration = 0;
for (int i = 0; i < animationDrawable.getNumberOfFrames(); i++) {
totalFrameDuration += animationDrawable.getDuration(i);
}
animationDrawable.start();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
animationDrawable.stop();
}
}, duration);
}

Animation Drawable with Sound in android?

I use the animation drawable functionality in my class.
I need to generate the sound while each frame of animation is loaded.Whether it is possible or not. I use the following code for animation:
<?xml version="1.0" encoding="utf-8"?>
<animation-list android:id="#+id/handimation" android:oneshot="false"
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/count3" android:duration="650" />
<item android:drawable="#drawable/count2" android:duration="650" />
<item android:drawable="#drawable/count1" android:duration="650" />
<item android:drawable="#drawable/go" android:duration="650" />
</animation-list>
My Java:
AnimationDrawable frameAnimation;
ImageView animatedimage ;
animatedimage = (ImageView)findViewById(R.id.rcount);
final MyAnimationRoutineStart animationStart =
new MyAnimationRoutineStart();
final MyAnimationRoutineStop animationStop =
new MyAnimationRoutineStop();
animatedimage.setBackgroundResource(R.drawable.spin);
frameAnimation = (AnimationDrawable) animatedimage.getBackground();
Timer animateTimerStart = new Timer(false);
animateTimerStart.schedule(animationStart, 100);
Timer animateTimerStop = new Timer(false);
animateTimerStop.schedule(animationStop, 2500);
class MyAnimationRoutineStart extends TimerTask
{
MyAnimationRoutineStart()
{
}
public void run()
{
// Start the animation (looped playback by default).
frameAnimation.start();
}
}
class MyAnimationRoutineStop extends TimerTask
{
MyAnimationRoutineStop()
{
}
public void run()
{
frameAnimation.stop();
// stop the animation (looped playback by default).
videoName=camcorderView.startRecording();
counter = 0;
counterFlag = true;
counterThread.start();
}
}
I don't know where to generate the sound.
Any one suggest some idea.
Thanks.
I achieved that using a handler. Inside the handler, I start and play the sound and delay the handler message for the duration of each animation frame. It is working fine.

Change source image for image view when pressed

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.

Categories

Resources