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>