单击按钮时,java ImageView背景不会平稳变化
我正在编写一个简单的应用程序,可以在点击按钮时随机更改应用程序背景
我有一个arraylist,其中包含应用程序应该使用的5个图像id:
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);
我的布局xml文件中有两个按钮,分别用于下一个和上一个。两者都应该在单击时更改应用程序背景
我更改此arraylist中的图像背景:
iM.setBackgroundResource(imageID.get(r.nextInt(5)));
我的布局xml如下所示:
<RelativeLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:id="@+id/parentLayout"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent" >
<ImageView
安卓:id="@+id/imageView1"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content" />
<Button
安卓:id="@+id/button1"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignParentBottom="true"
安卓:layout_alignParentLeft="true"
安卓:layout_marginBottom="76dp"
安卓:onClick="previous"
安卓:text="Previous" />
<Button
安卓:id="@+id/button2"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_alignBaseline="@+id/button1"
安卓:layout_alignBottom="@+id/button1"
安卓:layout_alignParentRight="true"
安卓:onClick="next"
安卓:text="Next" />
</RelativeLayout>
在点击按钮时一切都很好,ImageView的背景变化如我所料,但问题是背景变化不平稳
它会挂一段时间。可能是主ui线程将被阻塞1或2秒,这看起来像是应用程序挂起
挂起意味着:一些时间按钮保持点击几秒钟
我试过,但没有成功。有没有办法让它顺利改变
# 1 楼答案
你需要使用缓存,以节省时间,而不是每次图像膨胀 像这样:
Drawable image_frame_green = getResources().getDrawable( R.drawable.frame_green);