2015-04-06 121 views
1

我将FrameLayout作为根布局进行布局。定期更改背景图像ImageView

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

我需要定期更改无限循环中的一些图像(某些条件),所以像幻灯片一样。
我试图使用处理程序,但当我改变我得到OutOfMemory错误。
我也试过ImageSwitcher,但它似乎不能正常工作。
请给出一个例子或建议如何正确遵循Android的所有设计模式,thx。

+0

您可以使用定时器在经过一定时间后更改图像视图的可绘制 – Phil3992 2015-04-06 13:36:38

+0

使用视图寻呼机以所描述的时间间隔滑动图像 – Anuj 2015-04-06 13:36:50

+0

尝试使用AsyncTask加载新图像并在改变时播放一些动画它被加载后的图像。在时间间隔内执行Handler中的asynctask。 – 2015-04-06 13:37:53

回答

0

Hye在那里,我最近搜索这个问题,并遇到了一个很好的解决方案,因为它不适用自动密度的图像缩放和使用它们。

1把所有的图片在res /绘制-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); 
      } 
    } 
}; 

全部完成了,希望我帮了你。