您的位置:首页 > 移动开发 > Android开发

android ImageSwitcher 切换图片

2011-05-05 15:41 555 查看
ImageSwitcher可切换显示图片,实现类似windows图片查看器,上一张,下一张的功能,直接上代码:

public class ActivityMain extends Activity implements ViewSwitcher.ViewFactory{

private ImageSwitcher switcher;
private Button forward;
private Button next;
//图片索引
private int index = 0;
//显示的图片资源
private List<Drawable> list = new ArrayList<Drawable>();

/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

forward = (Button) findViewById(R.id.forward);
next = (Button) findViewById(R.id.next);

switcher = (ImageSwitcher) findViewById(R.id.image);

if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/test";
File folder = new File(path);
for(File file : folder.listFiles()){
list.add(Drawable.createFromPath(file.getAbsolutePath()));
}
}
//必须设置switcher的ViewFactory
switcher.setFactory(this);
if(list.size() > 0){
switcher.setImageDrawable(list.get(0));
}

//上一张
forward.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
index -- ;
if(index < 0) {
index = list.size() - 1;
}
switcher.setImageDrawable(list.get(index));
}
});
//下一张
next.setOnClickListener(new View.OnClickListener(){

@Override
public void onClick(View view) {
index ++ ;
if(index >= list.size()) {
index = 0;
}
switcher.setImageDrawable(list.get(index));
}
});
}
//用于显示图片
@Override
public View makeView() {
return new ImageView(this);
}
}

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageSwitcher
android:id="@+id/image"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/forward"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="forward"
/>
<Button
android:id="@+id/next"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="next"
/>

</LinearLayout>
</ScrollView>


本文出自 “学习笔记” 博客,请务必保留此出处http://maxuefeng.blog.51cto.com/1876326/559968
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: