如何让ImageSwitcher自动运行

时间:2015-02-25 17:48:34

标签: android android-layout

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

这是我的代码

public class MainActivity extends Activity

{
    私人ImageSwitcher imageSwitcher;

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();
} 

}

1 个答案:

答案 0 :(得分:1)

你可以在你的onCreate上调用方法start(null)(带有null参数),就是这样,如果你想让它停止,那么当计时器启动时用null参数调用stop方法。