Text Animation and Background change - java

I'm stuck and need help.
How can I add animations like on the picture. I want the color of the background and text to be smoothly automatically changed 1 sec after the app is launched. And to be like a cycle. Meanwhile an icon is impulsing.

You can use Property Animation for changing color
int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(500); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animator) {
textView.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
Use alpha animations to fade in and out the textchanging So on repeat is when it is fading back in so you can update the text at that time
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(1);
anim.setRepeatMode(Animation.REVERSE);
txtLabel.startAnimation(anim);
anim.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
txtLabel.setText("my next Text"); //for fading back in
}
});
You can use the same animation for alpha on a bitmap or imageView to pulse in and out as well.
AlphaAnimation animPulse = new AlphaAnimation(1.0f, 0.0f);
animPulse.setDuration(500);
animPulse.setRepeatCount(Animation.INFINITE);
animPulse.setRepeatMode(Animation.REVERSE);
imgPulse.startAnimation(animPulse);
Then of course just put in your
public void onCreate(){
Handler mMainHandler = new Handler(Looper.prepareMainLooper());
mMainHandler.postDelay(new Runnable(){
doAnimations();
}, 1000);
}
Then simply lump all your animations into methods and call them from doAnimations. Good luck.

Here you go..
I did the code to change color of background layout and text. Currently I did for random colors, if you need pre-defined colors, please let me know. Below is my code
activity_main.xml
`
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.golevr.background_animation.MainActivity"
android:id="#+id/constraint">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="30dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
`
MainActivity.java
`
public class MainActivity extends AppCompatActivity {
// Move your declarations here if you intend on using them after the onCreate() method
ConstraintLayout layout;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Inflate your objects
layout = (ConstraintLayout) findViewById(R.id.constraint);
textView = (TextView) findViewById(R.id.textView);
// We change the color to RED for the first time as the program loads
layout.setBackgroundColor(Color.RED);
// We change the color to GREEN for the first time as the program loads
textView.setTextColor(Color.GREEN);
// Create the timer object which will run the desired operation on a schedule or at a given time
Timer timer = new Timer();
// Create a task which the timer will execute. This should be an implementation of the TimerTask interface.
// I have created an inner class below which fits the bill.
MyTimer myTimer = new MyTimer();
// We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
timer.schedule(myTimer,1000,1000);
}
// An inner class which is an implementation of the TImerTask interface to be used by the Timer.
class MyTimer extends TimerTask{
#Override
public void run() {
// This runs in a background thread.
// We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
runOnUiThread(new Runnable() {
#Override
public void run() {
Random rand = new Random();
// The random generator creates values between [0,256) for use as RGB values used below to create a random color
// We call the RelativeLayout object and we change the color. The first parameter in argb() is the alpha.
layout.setBackgroundColor(Color.argb(255, rand.nextInt(256),rand.nextInt(256),rand.nextInt(256)));
textView.setTextColor(Color.argb(222,rand.nextInt(222),rand.nextInt(222),rand.nextInt(222)));
}
});
}
}
}
`
Is this what you want?

Related

Ripple Effect On ImageView not triggering

I have a RecyclerView with ImageViews in each item.
I set onClickListener for the ImageViews in onBindViewHolder as follows:
holder.starIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO: logic
}
});
The ripple effect worked fine until I added the following logic to onClick. This logic changes the Drawable for the ImageView.
holder.starIV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == holder.starIV.getId()) {
ListItem clickedItem = mDataset.get(position);
ListItem updatedItem = new ListItem(clickedItem);
if (clickedItem.getStarState() == STAR_ON) {
updatedItem.setStarState(STAR_OFF);
updatedItem.setStarDrawable(
ContextCompat.getDrawable(
v.getContext(),R.drawable.ic_star_border_24px));
}
else if (clickedItem.getStarState() == STAR_OFF) {
updatedItem.setStarState(STAR_ON);
updatedItem.setStarDrawable(
ContextCompat.getDrawable(
v.getContext(),R.drawable.ic_star_24px));
}
mDataset.set(position,updatedItem);
notifyDataSetChanged();
}
}
});
Now, I get no ripple effect at all. Here's the XML for the ImageView:
<ImageView
android:id="#+id/list_item_star"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:paddingLeft="4dp"
android:paddingRight="16dp"
android:src="#drawable/ic_star_border_24px"
android:clickable="true"
android:background="?attr/selectableItemBackgroundBorderless"
android:drawSelectorOnTop="true"
/>
The ripple effect works normally again when i comment out the logic part in onClick.
Have I implemented the above correctly?
What change would you suggest to get the ripple effect working correctly?
EDIT: It appears that changing the Drawable is interfering with the ripple animation. So i moved all the logic to an AsyncTask with a small delay to allow the animation to finish. This seems to work, but I feel this solution is not elegant. Here's the AsyncTask:
class DoLogix extends AsyncTask<Integer, Integer, Void> {
#Override
protected Void doInBackground(Integer... params) {
try{Thread.sleep(125);}catch (Exception e) {}
publishProgress(params[0]);
return null;
}
protected void onProgressUpdate(Integer... val) {
ListItem clickedItem = mDataset.get(val[0]);
ListItem updatedItem = new ListItem(clickedItem);
if (clickedItem.getStarState() == STAR_ON) {
updatedItem.setStarState(STAR_OFF);
updatedItem.setStarDrawable(starBorder);
}
else if (clickedItem.getStarState() == STAR_OFF) {
updatedItem.setStarState(STAR_ON);
updatedItem.setStarDrawable(star);
}
mDataset.set(val[0],updatedItem);
notifyDataSetChanged();
}
}
u can set a ripple drawable as the foreground of ur imageview.
add below code to your parent layout
android:clickable="true"
android:focusable="true"
android:background="?attr/selectableItemBackgroundBorderless"

How to translate ImageView right and left in Activity class continuously

I want to move ImageView (man.png) from right to left in Activity class(implements Runnable). I am using
Man.setTranslationX(float x); to move... Here is my code Man is not moving by run() method ..
public class PlayScreen extends Activity implements Runnable{
float ManX=100;
Thread thread=new Thread(this);
//some code here(removed)
public void ManImageView() {
Man = (ImageView)findViewById(R.id.stickman);
Man.setVisibility(ImageView.VISIBLE);
thread.start();
}
#Override
public void run(){
Man.setTranslationX(ManX);
ManX++;
try{
thread.sleep(500);}
catch{
}
}
is there any way to update ur screen continuously like invalidate(); method in View class.. or there is some problem with Thread running??? Here is .xml of ImageView
<ImageView
android:id="#+id/stickman"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginLeft="50sp"
android:layout_marginBottom="15sp"
android:src="#drawable/image1"/>
Please Help

How to change images in imageview every n number of seconds

I have made an array that has all the images in int and i want to change those images every 3 seconds in the imageView, I have tries all the solutions I could find but was showing some error, I can't figure it out .
java file (home.java)
/**
* Created by sukhvir on 17/04/2015.
*/
public class home extends android.support.v4.app.Fragment {
ImageView MyImageView;
int[] imageArray = { R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5 };
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(R.layout.home, container, false);
}
}
xml file(home.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Best option to achieve your requirement is You should use Timer to change Image each of 3 seconds as follows.
// Declare globally
private int position = -1;
/**
* This timer will call each of the seconds.
*/
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
// As timer is not a Main/UI thread need to do all UI task on runOnUiThread
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// increase your position so new image will show
position++;
// check whether position increased to length then set it to 0
// so it will show images in circuler
if (position >= imageArray.length)
position = 0;
// Set Image
MyImageView.setImageResource(imageArray[position]);
}
});
}
}, 0, 3000);
// where 0 is for start now and 3000 (3 second) is for interval to change image as you mentioned in question
use a CountDownTimer here is how: How to make a countdown Timer in android?
and change the image view background inside onFinish().
hope this will work out for you
first define a runnable
private Runnable runnable = new Runnable() {
#Override
public void run() {
changeImage(pos);
}
};
Than create a handler
private Handler handler;
handler = new Handler(Looper.getMainLooper());
In your changeImage method
private void changeImage(int pos) {
yourImageView.setImageResource(imageArray[pos]);
handler.postDelayed(runnable, duration);
}
Start and stop runnable with:
handler.postDelayed(runnable, duration);
handler.removeCallbacks(runnable);
I hope this'll help you. Good luck.

Creating a Singleton CountDownTimer in Android

I'm a beginner in android and I've written an activity. It contains a CountDownTimer that counts down from a particular value. It also contains a Button that loads text information and a textview to display count.
Below is the code for Activity1:
public class Screen extends Activity1 implements OnClickListener {
private static final int MILLIS_PER_SECOND = 1000;
private static final int SECONDS_TO_COUNTDOWN = 1;
TextView Time;
int totaltime;
Button startTimer, howTo, pause;
protected CountDownTimer MyTimer;
int PracticeCount;
long tot;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pushupscreen);
getRefs();
getSpeed();
getCount();
setTotalTime();
startTimer.setOnClickListener(this);
pause.setOnClickListener(this);
}
private void getRefs() {
// Initialize layout resources
Time = (TextView) findViewById(R.id.tvTime);
startTimer = (Button) findViewById(R.id.bStart);
howTo = (Button) findViewById(R.id.btHowTo);
pause = (Button) findViewById(R.id.bPause);
howTo.setOnClickListener(this);
}
private void getTheCount() {
//get count from SharedPreferences
}
private void getSpeed() {
//get speed from SharedPreferences
}
private void setCount(){
totalTime=speed*count;}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == startTimer) {
try {
showTimer(time);
} catch (NumberFormatException e) {
// method ignores invalid (non-integer) input and waits
// for something it cant use
}
} else if (v == pause) {
MyTimer.cancel();
Timer.setText("Resume");
} else if (v == howTo) {
//Launch screen containing information
}
}
private void showTimer(long time) {
if (MyTimer != null) {
MyTimer.cancel();
}
MyTimer = new CountDownTimer(tot2, MILLIS_PER_SECOND) {
#Override
public void onTick(long millisUntilFinished) {
tot = millisUntilFinished;
long seconds = millisUntilFinished / 1000;
Time.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
Time.setText("KABOOM!");
}
}.start();
}
}
And here is the layout file for this:
<TextView
android:id="#+id/tvTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:padding="10dip"
android:text="#string/starttime"
android:textSize="60sp" />
<Button
android:id="#+id/bStart"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:text="Start" />
<Button
android:id="#+id/bPause"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:layout_toRightOf="#+id/btHowTo"
android:text="Pause" />
<TextView
android:id="#+id/tvCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btHowTo"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:text="25"
android:textSize="80sp"
android:textAlignment="center"/>
My questions:
1.How do I create 4 activities that use the same layout and the same timer? Each Activity loads a different content in the textview and a different screen on the click of HowTo button.
2.How can Activity1 be designed to run for 1/4th the time set and pass remaining time to Activity2? Is it possible?
I would really appreciate any help and advice that you can provide. Thanks.
A couple things here.
Its very easy to re-use layouts. In each activity's onCreate you would just call:
setContentView(R.layout.pushupscreen); The pushupscreen.xml file can be shared across all activities this way.
What you probably want to do is persist a timestamp to some common data source for all the activities. This could be a write to a SharedPreferences file: Documentation here. Then as each activity resumes, check how much time has already passed by comparing this timestamp to the current timestamp. You could also pass the timestamp as an extra in the intent to start up the subsequent activities. The documentation for that can be found here and here
You could make a custom control, which is basically a new class which inherits some other control's class (for example a LinearLayout or a RelativeLayout). You could then load a view's XML to your new layout or programmatically create new controls inside your control. More info here:
Custom components in Android
After a 1/4 of your countdown period, you can create and send an Intent to start a new activity in the onTick method. You can also put the remaining 3/4 as a millisecond value (of type long) in an intent extra. You can then obtain this value in the new activity and invoke a custom CountDownTimer child there for the rest of your countdown. Then you can finally execute what you wish after the countdown is done in the onFinish() method.

How to hide and display a view in front of a webview depending on user input

I'm currently working on a project where I use a webview packed in RelativeLayout and I placed a ImageButton in the left-bottom corner:
<RelativeLayout
android:id="#+id/relativeLayout_maincontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
/>
<ImageButton
android:id="#+id/imageButton_call"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="2dp"
android:src="#android:drawable/ic_menu_call" />
</RelativeLayout>
This works just fine. The next step I was thinking of is that the button can sometimes disturb my users, when they can't see the stuff behind the button... So I tried to hide the button after a few seconds and when the user is scrolling/touching/or whatever (just some user input) I'll display it and after a few seconds the button should disappear again. Like the zoom-in and zoom-out buttons in a webview. The best way would be to use the same functionality as these zoom buttons, but I couldn't find a way to do this. I created a function based on the knowledge of How to show a view for 3 seconds, and then hide it? :
private void startCallButtonHidingThread() {
Thread thread = new Thread() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
runOnUiThread(new Runnable() {
#Override
public void run() {
callButton.setVisibility(ImageButton.GONE);
}
});
}
};
thread.start();
}
That works great. The next step was to display the button when user input happens, so I tried things like that:
relativeLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
return false;
}
});
or that:
relativeLayout.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
}
});
and the same I tried on the webview. Most of the time it works just one time and then there is no reaction at all.
So if you have any idea or a better solution, please let me know.
I really appreciate your help!
I think it's android restriction. Try to use handler:
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:{
if(callButton.getVisibility() == ImageButton.GONE) callButton.setVisibility(ImageButton.VISIBLE);
startCallButtonHidingThread();
}
}
};
And your listener:
relativeLayout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
handler.sendEmptyMessage(1);
return false;
}
});

Categories