首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让ImageSwitcher自动运行

如何让ImageSwitcher自动运行
EN

Stack Overflow用户
提问于 2015-02-26 01:48:34
回答 1查看 1.5K关注 0票数 0

您好,我正在尝试使用ImageSwitcher我设法使它工作,但我有问题是,我需要按开始使它开始和停止使它停止,我希望它自动启动时,活动开始

这是我的代码

代码语言:javascript
复制
public class MainActivity extends Activity

{

代码语言:javascript
复制
 private ImageSwitcher imageSwitcher;
代码语言:javascript
复制
private int[] gallery = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e, R.drawable.f};

private int position = 0;

private Timer timer = null;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);

    imageSwitcher.setFactory(new ViewFactory() {

         public View makeView() 
         {
             return new ImageView(MainActivity.this);
         } 
     });

     // Set animations http://danielme.com/2013/08/18/diseno-android-transiciones-entre-activities/
     Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
     Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
     imageSwitcher.setInAnimation(fadeIn);
     imageSwitcher.setOutAnimation(fadeOut);         
}



//////////////////////BUTTONS

public void start(View button)
{        
    timer = new Timer();
    timer.scheduleAtFixedRate(new TimerTask() {

    public void run() {
        // avoid exception: "Only the original thread that created a view hierarchy can touch its views"
        runOnUiThread(new Runnable() {
             public void run() {
                 imageSwitcher.setImageResource(gallery[position]);
                    position++;
                    if (position == 6)
                    {
                        position = 0;
                    }
            }
        });
    }

    }, 0, 2500);

}

public void stop(View button)
{   
    timer.cancel();
} 

}

EN

回答 1

Stack Overflow用户

发布于 2015-11-05 23:52:38

你只需要在你的onCreate上调用方法start( null ) (带null参数)就行了,如果你想让它停止,那么在定时器启动时调用带null参数的stop方法。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28726069

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档