ImageSwitcher01.java:
package com.ImageSwitcher01;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher.ViewFactory;
public class ImageSwitcher01 extends Activity implements OnClickListener,ViewFactory
{
//图片资源
private static final Integer[] imagelist=
{
R.drawable.img1,
R.drawable.img2,
R.drawable.img3
};
private ImageSwitcher mSwitcher;
private static int index=0;
private static final int BUTTON_DWON_ID=0x123456;
private static final int BUTTON_UP_ID=0x123457;
private static final int SWITCHER_ID=0x123458;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main_view=new LinearLayout(this);
mSwitcher=new ImageSwitcher(this);
//在线性布局中添加ImageSwitcher视图
main_view.addView(mSwitcher);
//设置ImageSwitcher对象ID
mSwitcher.setId(SWITCHER_ID);
//设置ImageSwitcher对象的数据源
mSwitcher.setFactory(this);
mSwitcher.setImageResource(imagelist[index]);
setContentView(main_view);
//下一张按钮
Button next=new Button(this);
next.setId(BUTTON_DWON_ID);
next.setText("next");
next.setOnClickListener(this);
LinearLayout.LayoutParams param=new LinearLayout.LayoutParams(100,100);
main_view.addView(next,param);
//上一张按钮
Button pre=new Button(this);
pre.setId(BUTTON_UP_ID);
pre.setText("pre");
pre.setOnClickListener(this);
main_view.addView(pre,param);
}
//事件监听
public void onClick(View v)
{
switch (v.getId())
{
//下一页
case BUTTON_DWON_ID:
index++;
if(index>=imagelist.length)
{
index=0;
}
//ImageSwitcher对象资源索引
mSwitcher.setImageResource(imagelist[index]);
break;
//上一页
case BUTTON_UP_ID:
index--;
if(index<0)
{
index=imagelist.length-1;
}
mSwitcher.setImageResource(imagelist[index]);
break;
default:
break;
}
}
public View makeView()
{
//将所有图片通过ImageView来显示
return new ImageView(this);
}
}