定期更改背景图像ImageView

时间:2015-04-06 13:33:41

标签: android multithreading performance android-layout imageview

我将FrameLayout布局为根布局。

<FrameLayout 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"
 >

    <ImageView
        android:id="@+id/background_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/init_image"
        android:scaleType="centerCrop">
    </ImageView>

......
......
</FrameLayout>

我需要在无限循环(某些条件)中定期更改一些图像,以便进行幻灯片放映 我试过使用Handler但是当我改变时我得到OutOfMemory错误。
我也试过ImageSwitcher,但似乎没有正常工作 请举例说明如何按照Android的所有设计模式正确实现它,thx。

1 个答案:

答案 0 :(得分:0)

Hye那里,我最近正在寻找这个问题并且遇到了一个很好的解决方案,因为它没有应用基于图像的自动密度缩放并按原样使用它们。

1-将所有图像放在res / drawable-nodpi文件夹中,您必须创建此文件夹,因为它不存在。

2 - 让它们在无限循环中自动从一个变为另一个。

int images[] = { R.drawable.background_1, 
        R.drawable.background_2,
        R.drawable.background_3, 
        R.drawable.background_4,
        R.drawable.background_5, 
        R.drawable.background_6,
        R.drawable.background_7 }; // i've these images in **res/drawable-nodpi**

这是onCreate方法

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView = (ImageView) findViewById(R.id.imageView_Animated); 

    handler.postDelayed(changeImage, 5000); // after every 5secs it will change image.

 }

现在这里是处理所有图像变化的部分,在onCreate之外做这个。

    Runnable changeImage = new Runnable() {

    @Override
    public void run() {

        if (count >6) {
            handler.removeCallbacks(changeImage);
        } else {

            if (count >= 6)
                count = 0;
            AlphaAnimation animation1 = new AlphaAnimation(0.5f, 1.0f); //here is a bit of animation for ya ;)
            animation1.setDuration(5000);
            animation1.setStartOffset(1300); //time for that color effect
            animation1.setFillAfter(true);
            imageView.startAnimation(animation1);
            imageView.setBackgroundResource(images[count++]);
            handler.postDelayed(changeImage, 5000);
            }
    }
};

一切都完成了,希望我帮助过你。

相关问题