I would like to make an animation, I have 10 images of a ball and I want to do:
Image1 visible, all the other images hidden
Image2 visible all the other images hidden
...
Image10 visible all the other images hidden
Should I do that in one animation (how?) or should I create a java method showImage(String pathimage) which would show the image located at pathimage and hide the others? Could I put any idea of time delay with using
handler.postDelayed(new Runnable() {
public void run() { }
}
EDIT, here is my code
The problem is that run() is always called in what seems to be an infinite loop. But I don't see where is my error
GAMEACTIVITY
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
ImageView image2 = (ImageView) findViewById(R.id.imageView3);
image2.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
myAsyncRunnable mar = new myAsyncRunnable(GameActivity.this);
mar.execute(null);
PhotoTask photoTask = new PhotoTask(camera,surfaceCamera,isPreview,holder,GameActivity.this);
photoTask.execute(null);
Log.w("GAMEACTIVITY","PHOTOTASK");
return false;
}
});
}
My Async Task
public class myAsyncRunnable extends AsyncTask<Void, Boolean, Void> {
GameActivity gameactivity;
#Override
protected Void doInBackground(Void... params) {
pull();
return null;
}
public myAsyncRunnable(GameActivity gameactivity) {
super();
this.gameactivity = gameactivity;
}
public void pull() {
final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
final int drawables[] = new int[] {R.drawable.pull2,R.drawable.pull3,R.drawable.pull4,R.drawable.pull5,R.drawable.pull6,R.drawable.pull7};
Runnable runnable = new Runnable() {
#Override
public void run() {
for (int i=0;i<drawables.length;i++) {
image3.setImageResource(drawables[i]);
gameactivity.handler.postDelayed(this, 500);
Log.w("asyncrunnable","run"+i);
}
}
};
gameactivity.handler.post(runnable);
}
}
You should not create 10 ImageViews to do such animation.
Only one ImageView should suffice! Use a handler to update the Image using any flavor of setImage every x milliseconds or so.
Initialize the images in an array and the current image in an integer :
int drawables[] = new int[] {R.drawable.image1, R.drawable.image2, ...};
int mCurrent = 0;
Then initialize your updater:
Runnable runnable = new Runnable() {
#Override
public void run() {
if(mCurrent>=drawables.length)mCurrent=0;
imageView.setImageResource(drawables[mCurrent]);
mHandler.postDelayed(this, 3000); //every 3 seconds
}
};
Finally when you want to start, just post the runnable:
mHandler.post(runnable);
Your code is wrong:
Try this pull function (although i do not really approve the whole code style but no time to fix that)
public void pull() {
final ImageView image3 = (ImageView) gameactivity.findViewById(R.id.imageView3);
final int drawables[] = new int[] {R.drawable.pull2,R.drawable.pull3,R.drawable.pull4,R.drawable.pull5,R.drawable.pull6,R.drawable.pull7};
for (int i=0;i<drawables.length;i++) {
final int j = i;
Runnable runnable = new Runnable() {
#Override
public void run() {
image3.setImageResource(drawables[j]);
}
};
gameactivity.handler.postDelayed(this, 500 * i);
Log.w("asyncrunnable","run"+i);
}
}
}
Related
Here my transition and reverse transition happens only once not 10 times, Can u tell me where I'm wrong ??
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for(int i=0;i<10;i++)
{
Resources res = getApplicationContext().getResources();
Drawable background[] = new Drawable[2];
background[0] = res.getDrawable(R.drawable.shapes);
background[1] = res.getDrawable(R.drawable.large_shape);
final TransitionDrawable transition = new TransitionDrawable(background);
ImageView imgview = findViewById(R.id.transitimage);
imgview.setImageDrawable(transition);
Runnable r1 = new Runnable() {
#Override
public void run() {
transition.startTransition(2000);
}
};
Runnable r2 = new Runnable() {
#Override
public void run() {
transition.reverseTransition(2000);
}
};
Handler h = new Handler();
h.postDelayed(r1, 0);
h.postDelayed(r2, 2000);
}
}
}
public void repeat() {
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
if (i>9) { // i is a field,its initial value equals 0
cancel(); // stop timer
}
if (flag) {
transition.startTransition(2000);
} else {
transition.reverseTransition(2000);
}
flag = !flag;
i += 1;
}
public void onFinish() {
repeat();
}
}.start();
}
Call above function in some place.
I m trying to load images in an image switcher from Http server. I didnot find any function like setImageBitmap. So I tried using setImageURI() , but its not getting loaded.
I am tring to switch image after every 3 sec. This is the code. When i m running the codes image is not getting loaded. And app is also getting crased.
String arr[]={"http://192.168.1.7/photos/dummy/1.jpg","http://192.168.1.7/photos/dummy/2.jpg","http://192.168.1.7/photos/dummy/3.jpg"}
dailyWear = (ImageSwitcher) getActivity().findViewById(R.id.imageDailyWear);
dailyWear.setFactory(new ViewSwitcher.ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_XY);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
return myView;
}
});
dailyWear.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_in_left));
dailyWear.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right));
final Handler handler = new Handler();
final Runnable r = new Runnable() {
int i=0;
public void run() {
weddingWear.setImageURI(Uri.parse(arr[i));
i++;
if (i >= arr.length()-1)
i = 0;
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(r, 1000);
what you can do is first get these images and store it in arraylist of bitmap that you can switch these images
private Context mContext;
private int index = 0;
private final int interval = 3000;
private final int DURATION=1500;
public void animate_Images_In_Top_View_After_Every_Three_Seconds(
ImageSwitcher imageSwitcher, final ArrayList<Bitmap> _Images_List) {
android.view.animation.Animation aniIn = AnimationUtils.loadAnimation(mContext,
android.R.anim.fade_in);
aniIn.setDuration(DURATION);
android.view.animation.Animation aniOut = AnimationUtils.loadAnimation(mContext,
android.R.anim.fade_out);
aniOut.setDuration(DURATION);
final ImageSwitcher _ImageSwitcher = imageSwitcher;
_ImageSwitcher.setInAnimation(aniIn);
_ImageSwitcher.setOutAnimation(aniOut);
_ImageSwitcher.setFactory((android.widget.ViewSwitcher.ViewFactory) mContext);
_ImageSwitcher.setImageDrawable(new BitmapDrawable(_Images_List.get(index)));
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
index++;
index = index % _Images_List.size();
// Log.d("Intro Screen", "Change Image " + index);
_ImageSwitcher.setImageDrawable(new BitmapDrawable(_Images_List.get(index)));
handler.postDelayed(this, interval);
}
};
handler.postDelayed(runnable, interval);
}
and i am using fade in and out animation you can set to your own need.
This my java code how I implemented.
new Thread(new Runnable() {
public void run() {
int count=0;
while (true) {
if(count>5)
count=0;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println(""+e);
}
ImageView image = (ImageView) findViewById(R.id.slider);
image.setImageResource(pics[count]);
count++;
}
}
}).start();
I have created a separate Thread to change the images dynamically
Thats because you're trying to set a picture from thread different than UI thread. And you're only allowed to change the UI from the UI thread.
final ImageView image = (ImageView) findViewById(R.id.slider);
image.post(new Runnable() {
#Override
public void run() {
image.setImageResource(pics[count]);
});
This will post your changes into the UI thread's queue.
You can achieve it using the Handler's postDelayed method
public class MyRunnable implements Runnable {
private ImageView imageView;
private boolean exit = false;
public MyRunnable(ImageView n) {
imageView = n;
}
private void setExit() {
exit = true;
}
#Override
public void run() {
if (exit) {
imageView.removeCallbacks(null);
imageView = null;
return;
}
imageView.setImageResource(pics[count++%5]);
imageView.postDelayed(this, 1000);
}
}
Declare a member:
MyRunnable mRunnable = null;
onResume
ImageView image = (ImageView) findViewById(R.id.slider);
image.postDelayed(mRunnable = new MyRunnable(image), 1000);
and onPause call
mRunnable.setExit();
Or you could put your image in Drawable and then use
ImageView.setImageResource (int resId)
Didn't tried but should work fine
I am using ImageDownloader class to get images from server and getting these images links using an ArrayList. After downloading the Image I am setting the Image as background of the layout. All is working but I want to change these Images after a specific time interval and set as background different images. I have gone through many posts here but didn't get what I want. As I have all Images links in ArrayList, so how can I set a timer to change the images, coming from that ArrayList.It always show me the first Image at index zero even I have set a timer but the same Image is showing again? Please help me if someone has any code example and see my code what to change there?
final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
item = list.get(i);
}
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage);
I do not know about ImageLoader component but scheduling a timer on a view is quite easy in Android.(Without any additional Object)
final ImageView bgImage=(ImageView) findViewById(R.id.image);
...
new Runnable() {
int updateInterval = 1000; //=one second
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
bgImage.postDelayed(this, updateInterval);
}
}.run();
You can change this template as you wish, suppose I want to stop this timer, for this purpose I have to add a stop method to my runnable(This stop method acts synchronized and do not cause inconsistency in timer inner codes):
Runnable myRunnable = new Runnable() {
int updateInterval = 1000; //=one second
boolean stop = false;
public void stop() {
this.stop = true;
}
#Override
public void run() {
// Any code which goes here will be executed every 'updateInterval'
// change your background here
if(!stop) {
bgImage.postDelayed(this, updateInterval);
}
}
}.run();
Now I can stop it by myRunnable.stop();
EDIT :
You should iterate your array of URLs and pass one of them to your downloader. It can be accomplished by this snippet code:
int arraySize = list.size();
new Runnable() {
int currentIndex = 0;
int updateInterval = 1000; //=one second
#Override
public void run() {
currentIndex += 1;
if(currentIndex == arraySize){
currentIndex = 0;
}
item = list.get(currentIndex);
downloader.download(item.imageurl(), bgImage);
bgImage.postDelayed(this, updateInterval);
}
}.run();
Set up your ImageView like this:
<ImageView
android:id="#+id/imgBackground"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/app_name"
android:scaleType="fitXY" />
You can Use TimerTask to achieve this.
// Declaration and Initialization :
List<String> mImageUrl = new ArrayList<String>();
private ImageLoader mImageLoader = new ImageLoader(MainActivity.this);
Timer timer = new Timer(); // changed
int i = 0;
// Put this code in your onCreate :
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (i < mImageUrl.size()) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mImageLoader.DisplayImage(mImageUrl.get(i), img);
i++;
}
});
} else {
i = 0;
}
}
}, 0, 2000);
The timer task will start in 0 seconds and it will change the background every 2 seconds. You can change this as like as you want.
Its working fine. I have tested.
You can read more about the timertask here.
You can also cancel the timer with the help of timer.cancel() HIH.
final ImagesSerialized item;
final ImageView bgImage=(ImageView) findViewById(R.id.image);
ArrayList<ImagesSerialized> list;
control = (Controller) getApplicationContext();
list = (ArrayList<ImagesSerialized>) control.Table_Images.GetData();
for(int i=0; i<list.size(); i++)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
item = list.get(i);
downloader = new ImageDownloader();
downloader.download(item.imageurl(), bgImage)
}
});
}
Try this way hope this will help you for more improvement of your code...
you need "Aquery(AndroidQuery)" jar from this reference :
https://code.google.com/p/android-query/downloads/detail?name=android-query-full.0.24.3.jar
2.now add this jar on your project lib folder and add to build path or as library.
3.now it's time for code using "Aquery(AndroidQuery)" to download images from server(here is my demo code you can modified as per your requirement).
"activity_main.xml"
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imgFromServer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
<ProgressBar
android:id="#+id/pbrImageLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
</FrameLayout>
</LinearLayout>
"MyActivity.java"
public class MyActivity extends Activity{
private ImageView imgFromServer;
private ProgressBar pbrImageLoader;
private AQuery aQuery;
private int currentIndex;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgFromServer = (ImageView) findViewById(R.id.imgFromServer);
pbrImageLoader = (ProgressBar) findViewById(R.id.pbrImageLoader);
aQuery = new AQuery(this);
currentIndex=0;
final ArrayList<String> imageUrlListFromServer = new ArrayList<String>();
imageUrlListFromServer.add("http://www.mayoff.com/5-01cablecarDCP01934.jpg");
imageUrlListFromServer.add("http://www.allindiaflorist.com/imgs/arrangemen4.jpg");
imageUrlListFromServer.add("http://www.hdwallshub.com/files/submissions/cookie_monster_hd_wallpaper_1405239014.jpg");
imageUrlListFromServer.add("http://images4.fanpop.com/image/photos/17200000/Tangled-offical-wallpapers-tangled-17286338-1680-1050.jpg");
imageUrlListFromServer.add("http://wakpaper.com/large/Moons_wallpapers_4.jpg");
final Timer timer = new Timer();
downloadImagesFromServer(imageUrlListFromServer, 0, new ImageDownloadedListener() {
#Override
public void onDownloadFinish() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
imgFromServer.setImageBitmap(aQuery.getCachedImage(imageUrlListFromServer.get(currentIndex)));
if(currentIndex == imageUrlListFromServer.size()-1){
currentIndex=0;
}else{
currentIndex++;
}
}
});
}
},0,2000);
}
});
}
private void downloadImagesFromServer(final ArrayList<String> imageUrlList,final int index,final ImageDownloadedListener listener){
aQuery.progress(pbrImageLoader).ajax(imageUrlList.get(index), Bitmap.class, 0, new AjaxCallback<Bitmap>() {
#Override
public void callback(String url, Bitmap object, AjaxStatus status) {
super.callback(url, object, status);
if ((imageUrlList.size() - 1) == index) {
listener.onDownloadFinish();
} else {
downloadImagesFromServer(imageUrlList, index + 1, listener);
}
}
});
}
interface ImageDownloadedListener{
public void onDownloadFinish();
}
}
Note : "Aquery(AndroidQuery)" also cache images on local so it not get same images from server if it already downloaded.
try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}
I have a problem that I want to paste images on ImageView in Android and that images are periodically changed after some interval. Means one by one images shown in ImageView. I am doing this with the help of Thread in java but I got some problem that Thread is not attached and something. Please review my code given below and tell me the exact error and how to remove that error or give me some diffrent way for doing this.
package com.ex.thread;
import com.ex.thread.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
public class thread extends Activity implements Runnable{
/** Called when the activity is first created. */
public static Integer[] mThumbIds = {
R.drawable.al1,R.drawable.al2,R.drawable.al3,R.drawable.al4,
};
Thread th;
ImageView iv;
public void run()
{
for(int i=0;i<3;i++)
{
iv.setImageResource(mThumbIds[i]);
System.out.println("Sanat Pandey");
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
}
public void create()
{
Thread th = new Thread(new thread());
th.start();
try{
Thread.sleep(3000);
}catch(Exception e)
{
System.out.println(e);
}
}
#Override
public void onCreate(Bundle savedInstace)
{
super.onCreate(savedInstace);
setContentView(R.layout.main);
create();
}
}
Try this..It works out well...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);``
//
//
int []imageArray={R.drawable.img1,R.drawable.img2,R.drawable.img3};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i=0;
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1)
{
i=0;
}
handler.postDelayed(this, 50); //for interval...
}
};
handler.postDelayed(runnable, 2000); //for initial delay..
}
You can't use things in the UI thread from a background one. So this call:
iv.setImageResource(mThumbIds[i]);
Has to be done in the main thread. In fact you probably don't need a background thread at all to get the effect you're looking for. You can make that just an activity, no need to implement runnable. and then do something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
iv = (ImageView) findViewById(R.id.yourImageViewID);
int i = 0;
Runnable r = Runnable(){
public void run(){
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}
iv.postDelayed(r, 3000); //set to go off again in 3 seconds.
}
};
iv.postDelayed(r,3000); // set first time for 3 seconds
Try this
it's working
public class vv extends Activity {
int b[] = {R.drawable.a, R.drawable.m, R.drawable.b, R.drawable.j, R.drawable.er, R.drawable.chan, R.drawable.vv};
public ImageView i;
int z = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
i = (ImageView) findViewById(R.id.image);
i.setImageResource(b[0]);
Thread timer = new Thread() {
public void run() {
try {
sleep(2000);
for (z = 0; z < b.length + 2; z++) {
if (z < b.length) {
sleep(2000);
runOnUiThread(new Runnable() {
public void run() {
i.setImageResource(b[z]);
}
});
} else {
z = 0;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("finally");
}
}
};
timer.start();
}
}
try this code.the images was saved in drawable. please do insert a imageview in xml code. noted that the time interval for the following code is 1 sec.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
public ImageView iv;
public static Integer[] mThumbIds = {
R.drawable.pic1,R.drawable.pic2,R.drawable.pic3,R.drawable.pic4};
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.imageView);
i=0;
t.start();
}
Thread t = new Thread() {
#Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
iv.setImageResource(mThumbIds[i]);
i++;
if(i >= mThumbIds.length){
i = 0;
}}});}}
catch (InterruptedException e) {
}}};
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final int img[] = {R.drawable.flower1, R.drawable.flower2, R.drawable.flower3, R.drawable.flower4};
layout = (RelativeLayout) findViewById(R.id.activity_main);
final Handler handler=new Handler();
Runnable runnable = new Runnable() {
int i = 0;
#Override
public void run() {
layout.setBackgroundResource(img[i]);
i++;
if (i > img.length - 1) {
i = 0;
}
handler.postDelayed(this, 4000); //for interval 4s..
}
};handler.postDelayed(runnable, 100); //for initial delay..
}