Android continuous moving animation - android

I want to do an animation in which an image continuously keeps moving from top to bottom after every 3 seconds. I have achieved this using the following code
My XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="left|top"
android:baselineAligned="false"
android:background="#ffffff">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/layout1">
</RelativeLayout>
</LinearLayout>
My Activity class
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends AppCompatActivity {
private RelativeLayout layout1;
private TranslateAnimation moveDownwards;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
layout1 = (RelativeLayout) findViewById(R.id.layout1);
moveDownwards = new TranslateAnimation(0, 0, -100, 1000);
moveDownwards.setDuration(3000);
moveDownwards.setFillAfter(true);
startTimer();
}
#Override
protected void onResume() {
super.onResume();
startTimer();
}
private void startTimer() {
Timer timer = new Timer();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
#Override
public void run() {
ImageView iv1 = new ImageView(GameActivity.this);
iv1.setImageResource(R.drawable.c_orange);
layout1.addView(iv1);
iv1.startAnimation(moveDownwards);
}
});
}
};
timer.schedule(task,0,3000);
}
}
Above code is working fine but the animation is not consistent. For example, when I touch the screen while the image is moving, the smoothness of animation is disturbed and it becomes rough.
Is there any better way to achieve this???

There is no need to add a new Image view after every 3 sec. You can set repeatcount -1(INFINITE).
public class MainActivity extends Activity {
private TranslateAnimation moveDownwards;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
moveDownwards = new TranslateAnimation(0, 0, -100, 1000);
moveDownwards.setDuration(3000);
moveDownwards.setFillAfter(true);
moveDownwards.setRepeatCount(-1);
findViewById(R.id.image).startAnimation(moveDownwards);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start|top"
android:background="#ffffff" >
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</RelativeLayout>

Related

R.string vs R.id in android

I have some code that says
MainActivity.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView av; //UI reference
int textString = R.string.start;
int backgroundColor = Color.DKGRAY;
final Handler mHandler = new Handler();
// Create runnable for posting results to the UI thread
final Runnable mUpdateResults = new Runnable() {
public void run() {
av.setText(textString);
av.setBackgroundColor(backgroundColor);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
av = (TextView) findViewById(R.id.computation_status);
Button actionButton = (Button) findViewById(R.id.action1);
actionButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doWork();
}
});
}
//example of a computationally intensive action with UI updates
private void doWork() {
Thread thread = new Thread(new Runnable() {
public void run() {
textString=R.id.start;
backgroundColor = Color.DKGRAY;
mHandler.post(mUpdateResults);
computation(1);
textString=R.id.first;
backgroundColor = Color.BLUE;
mHandler.post(mUpdateResults);
computation(2);
textString=R.id.second;
backgroundColor = Color.GREEN;
mHandler.post(mUpdateResults);
}
});
thread.start();
}
final static int SIZE=1000; //large enough to take some time
double tmp;
private void computation(int val) {
for(int ii=0; ii<SIZE; ii++)
for(int jj=0; jj<SIZE; jj++)
tmp=val*Math.log(ii+1)/Math.log1p(jj+1);
}
}
activity_main.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">
<TextView android:id="#+id/computation_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000" />
<TextView
android:id="#+id/start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start textview" />
<TextView
android:id="#+id/first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+string/first" />
<TextView
android:id="#+id/second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/action1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
I know that if that was R.id.start then there would have to be a textview in the xml file named start. What do I do if I have R.string.start? Because making a textview doesn't work.
R.string.start is actually a reference to a string named start, not the string itself.
So, it's an int.
R.id are the ids for the views

Animation Translate using LayoutParams

Basically i want to create translate animation but for some reason i cannot use TranslateAnimation class. Anyway this is my code
main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
MainActivity.java
package com.test2;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.ImageView;
public class MainActivity extends Activity
{
private RelativeLayout layout;
private ImageView image;
private LayoutParams imageParams;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (RelativeLayout) findViewById(R.id.layout);
image = (ImageView) findViewById(R.id.image);
imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
image.setLayoutParams(imageParams);
layout.setOnClickListener(new ClickHandler());
}
class ClickHandler implements OnClickListener
{
public void onClick(View view)
{
// This is the animation part
for (int i = 0; i < 100; i++)
{
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
// repaint() in java
try
{
Thread.sleep(100);
}
catch (Exception e)
{
}
}
}
}
}
My problem is I need to do repaint() before using Thread.sleep otherwise the animation will not work and the object will just move to its final position. I've tried invalidate, requestLayout, requestDrawableState but none works. Any suggestion?
EDIT:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity
{
private RelativeLayout layout;
private ImageView image;
private LayoutParams imageParams;
private Timer timer;
private int i;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
layout = (RelativeLayout) findViewById(R.id.layout);
image = new ImageView(this);
image.setImageResource(R.drawable.ic_launcher);
imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
image.setLayoutParams(imageParams);
layout.addView(image);
i = 0;
timer = new Timer();
runOnUiThread
(
new Runnable()
{
public void run()
{
timer.scheduleAtFixedRate
(
new TimerTask()
{
#Override
public void run()
{
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
i++;
if (i == 15)
{
timer.cancel();
timer.purge();
}
}
}, 0, 100
);
}
}
);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
</RelativeLayout>
package com.example.example;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.app.Activity;
public class MainActivity extends Activity {
ImageView imageView;
RelativeLayout.LayoutParams params;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=new ImageView(this);
RelativeLayout main=(RelativeLayout)findViewById(R.id.main);
params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
imageView.setBackgroundResource(R.drawable.ic_launcher);
imageView.setLayoutParams(params);
main.addView(imageView);
final Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
params.leftMargin=i;
imageView.setLayoutParams(params);
i++;
if(i>=100){
timer.cancel();
timer.purge();
}
}
});
}
}, 0, 100);
}
}
you can use timer task instead of sleep
Like:-
int i=0;
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
imageParams.leftMargin = i;
image.setLayoutParams(imageParams);
i++;
if(i==100){
timer.cancel();
timer.purge();
}
}
}, 0, 1000);

How to update header layout text every seconds in any one activity and display in all screens?

header.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/txtTime"
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
android:layout_weight="1"
android:gravity="right" />
</LinearLayout>
i added header.xml in all my screen layouts...
<include
android:id="#+id/top_header"
layout="#layout/header" />
Now i want start timer and set text of every remaining seconds in text header txtTime...
So which screen i write code for countdown timer and set textview so all screen display time in textview..
can any one suggest me its possible to set text only one screen and display in all screen ?
Thanks
Please try below code . It will solve your prolem.
Follow below steps.
1) Make one BaseActivity Class.
2) Make One MainActivity Class and extend BaseActivity.
3) Make another SecondActivity class and extend BaseActivity.
Here i post all the classes you required .
What i do in BaseActivity ?
I create one Countdown Timer class called MyCount which will display
the remaining time . I create one boolean flag which set false by
default . so when user call setHeading() function of BaseActivity it
will check the falg if it false then start the timer and if it is true
then again set the timer and starts again .
BaseActivity
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.widget.TextView;
public abstract class BaseActivity extends Activity
{
private TextView textView = null;
public static MyCount counter = null;
private static boolean flag = false;
private static long millisUntilFinishedVariable = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
protected void setHeading(String message)
{
if(textView == null)
{
textView = (TextView)findViewById(R.id.textView);
if(textView != null)
textView.setText(message);
if(flag == false)
{
counter = new MyCount(30000, 1000);
counter.start();
}
else
{
counter.cancel();
counter = new MyCount(millisUntilFinishedVariable, 1000);
counter.start();
}
}
}
// countdowntimer is an abstract class, so extend it and fill in methods
public class MyCount extends CountDownTimer
{
public MyCount(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish()
{
textView.setText("done!"); //TextView object should be defined in onCreate
flag = false;
}
#Override
public void onTick(long millisUntilFinished)
{
millisUntilFinishedVariable = millisUntilFinished;
flag = true;
textView.setText("Left:" + millisUntilFinished/1000);// This will be called every Second.
}
}
}
MainActivity
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends BaseActivity
{
private Button buttonClick = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setHeading("Text From Main Activity");
buttonClick = (Button)findViewById(R.id.buttonClick);
buttonClick.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
startActivityForResult(new Intent(MainActivity.this,SecondActivity.class), 0);
}
});
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="#layout/header"/>
<Button
android:id="#+id/buttonClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="96dp"
android:layout_marginTop="68dp"
android:text="Second Activity" />
</RelativeLayout>
SecondActivity
import android.os.Bundle;
public class SecondActivity extends BaseActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
setHeading("From Second Activity");
}
}
second_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="#layout/header"/>
</RelativeLayout>
header.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:orientation="vertical" >
<TextView
android:id="#+id/textView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18.0sp"/>
</LinearLayout>
You can use the SharedPreferences to save the text to be set to all your screens. Then set the textViews with the saved text. You can set the textView in the onCreate() or onResume() of all the activities.

ViewFlipper causing null pointer exception

I have a program which uses view flipper I am getting a NullPointerException as follows when the activity is called. I wish to cycle through a set of images as long as the activity is being run.
06-13 18:52:05.358: E/AndroidRuntime(368): Caused by: java.lang.NullPointerException
Activity:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class MainMenuActivity extends Activity{
Handler handler;
Runnable runnable;
ViewFlipper imageSwitcher;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menupage);
imageSwitcher= (ViewFlipper) new ViewFlipper(this).findViewById(R.id.sportspersons);
this.viewchanger();
}
public void viewchanger()
{
imageSwitcher.setInAnimation(this, R.anim.fadein);
imageSwitcher.setOutAnimation(this, R.anim.fadeout);
ImageView i = new ImageView(this);
i.setBackgroundDrawable(getResources().getDrawable(R.drawable.jowens));
ImageView i2 = new ImageView(this);
i2.setBackgroundDrawable(getResources ().getDrawable(R.drawable.maradonna));
ImageView i3 = new ImageView(this);
i2.setBackgroundDrawable(getResources().getDrawable(R.drawable.mjordan));
ImageView i4 = new ImageView(this);
i2.setBackgroundDrawable(getResources().getDrawable(R.drawable.pele));
imageSwitcher.addView(i);
imageSwitcher.addView(i2);
imageSwitcher.addView(i3);
imageSwitcher.addView(i4);
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(runnable, 3000);
imageSwitcher.showNext();
}
};
handler.postDelayed(runnable, 500);
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="508dp"
android:layout_x="-4dp"
android:layout_y="-5dp"
android:scaleType="fitXY"
android:src="#drawable/mainmenu01" />
<ViewFlipper
android:id="#+id/sportspersons"
android:layout_width="86dp"
android:layout_height="91dp"
android:layout_x="38dp"
android:layout_y="373dp" />
</AbsoluteLayout>
You can try this way:
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(runnable, 3000);
imageSwitcher.setAutoStart(true);
imageSwitcher.startFlipping();
}
};
Change
imageSwitcher= (ViewFlipper) new ViewFlipper(this).findViewById(R.id.sportspersons);
To
imageSwitcher= (ViewFlipper) findViewById(R.id.sportspersons);
To add to Waqas Point.
You have serious issue in following piece of code.
runnable = new Runnable() {
#Override
public void run() {
handler.postDelayed(runnable, 3000);
imageSwitcher.showNext();
}
};
handler.postDelayed(runnable, 500);

android imgeview pause and clear

I have this code and I'm trying to read 2 images from the SD card and I don't know how to pause between the 2 images that I can have enough time to see each 1 of them. Also, I don't know how to clear the ImgeView after I display the 2 images
This is how I want it to go:
load first image -> wait for 5 sec -> load sec image-> wait for 5 sec clear the ImageView
MainActivity.java
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class ReadfromSD extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String imageInSD = "/sdcard/Hanud/AD2.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
ImageView myImageView = (ImageView) findViewById(R.id.imageview1);
myImageView.setImageBitmap(bitmap);
String imageInSD2 = "/sdcard/Hanud/AD1.jpg";
Bitmap bitmap2 = BitmapFactory.decodeFile(imageInSD2);
ImageView myImageView1 = (ImageView) findViewById(R.id.imageview1);
myImageView1.setImageBitmap(bitmap2);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ImageView
android:id="#+id/imageview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:scaleType="center" />
</LinearLayout>
public class ImgLoadAct extends Activity {
/** Called when the activity is first created. */
Timer timer;
ImageView myImageView;
TextView titleText;
Drawable img1Drawable;
Drawable img2Drawable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myImageView = (ImageView)findViewById(R.id.imageview1);
titleText=(TextView)findViewById(R.id.img_title);
img1Drawable=getResources().getDrawable(R.drawable.android_logo);
img2Drawable=getResources().getDrawable(R.drawable.apple_logo);
//Load Img1 android_logo
myImageView.setImageDrawable(img1Drawable);
titleText.setText("Img2 android_logo.png loaded");
timer=new Timer();
//delay amount of time(5s here) in milliseconds before first execution.
timer.schedule(loadImg2, 5000);
}
TimerTask loadImg2 = new TimerTask(){
#Override
//Load Img2
public void run() {
runOnUiThread(new Runnable(){
public void run() {
titleText.setText("Img2 apple_logo.png loaded");
myImageView.setImageDrawable(img2Drawable);
timer.cancel();
timer=new Timer();
timer.schedule(clearImg, 5000);
}
});
}
};
TimerTask clearImg = new TimerTask(){
#Override
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable(){
public void run() {
timer.cancel();
titleText.setText("Img cleared");
myImageView.setImageDrawable(null);
}
});
}
} ;
}
Src dowload:
http://www.everbox.com/f/UtxQ4gzfXBPTFZlcIXi3HQHGU4

Categories

Resources