android auto-switched ImageSwitcher

 

  First,ImageSwitcher use setImageDrawable and setBackgroundDrawable to set the content.You'll need Timer class if you want to switch the content automatically.However,you can't change the UI content in a Timer,so you need a handler to send the message:

private Timer switchTimer;
private ImageSwitcher imageSwitcher;
private Handler mDownloadHandler = new Handler() {
            @Override
            public void dispatchMessage(Message msg) {
                switch (msg.what) {
                    case MSG_ADS_REFRESH:
                        int count=adsList.size();
                        if(count>0){
                            curads=(curads+1)%count;
                            Bitmap t=ImageUtilities.getCachedCover(adsList.get(curads).id);
                            imageSwitcher.setImageDrawable(new BitmapDrawable(t));
                        }
                        break;
                    default:
                        break;
                }
                super.dispatchMessage(msg);
            }
        };
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main)
        
        imageSwitcher=(ImageSwitcher)findViewById(R.id.store_main_ads);
        imageSwitcher.setFactory(new ViewFactory() {
            
            @Override
            public View makeView() {
                ImageView iv = new ImageView(StoreMainActivity.this);
                ImageSwitcher.LayoutParams lp=new ImageSwitcher.LayoutParams(
                        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                lp.gravity=Gravity.CENTER;
                iv.setLayoutParams(lp);
                return iv;
            }
        });
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,android.R.anim.fade_out));
        adsList=new ArrayList();
     switchTimer=new Timer();
        switchTimer.schedule(new TimerTask() {
            
            @Override
            public void run() {
                mDownloadHandler.sendEmptyMessage(MSG_ADS_REFRESH);
            }
        },10, 7000);
}

Don't forget to cancel the timer when you exit(ignore may be OK):

  @Override
    protected void onDestroy() {
        switchTimer.cancel();
        super.onDestroy();
    }

 The adsList in code is the content list of the ImageSwitch.

转载于:https://www.cnblogs.com/qiengo/archive/2012/04/19/2457709.html

你可能感兴趣的:(android auto-switched ImageSwitcher)