I am writing a simple app that changes the application background randomly on button click.
I have a arraylist that contains 5 id’s of images that the application should use:
ArrayList<Integer> imageID = new ArrayList<Integer>();
imageID.add(R.drawable.frame_blue);
imageID.add(R.drawable.frame_green);
imageID.add(R.drawable.frame_lilac);
imageID.add(R.drawable.frame_pink);
imageID.add(R.drawable.frame_yellow);
I have two buttons in my layout xml file for next and previous. Both should change Application background when clicked.
I change the image background from this arraylist:
iM.setBackgroundResource(imageID.get(r.nextInt(5)));
and my layout xml looks like:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="76dp"
android:onClick="previous"
android:text="Previous" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_alignParentRight="true"
android:onClick="next"
android:text="Next" />
</RelativeLayout>
All works fine on button click’s, ImageView background change as I expect, but the problem is the background is not changing smoothly.
It hangs some time. May be the main ui thread will be block for 1 or 2 second and this look like application hangs.
Hangs mean: Some time button remain clicked for a few seconds.
I tried asynctask did not have success. Is there a way to make it change smoothly?
you need to use caching in order to save time and not inflate every time the images
like this :
Drawable image_frame_green = getResources().getDrawable(
R.drawable.frame_green);