android auto-switched ImageSwitcher

本文详细介绍了如何使用Handler和Timer在Android中实现ImageSwitcher的自动内容切换功能,包括初始化配置、内容刷新逻辑以及退出时取消定时器的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值