package com.example.imageswitcher;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
/**
*
* @author TXF
*
* ImageSwitcher(图片切换器,无限循环。类似Windows的图片查看器)
*/
public class MainActivity extends Activity implements ViewFactory {
private ImageSwitcher mis;
private Integer[] imageIds = { R.drawable.a, R.drawable.b, R.drawable.c,
R.drawable.d, R.drawable.e };
private int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mis = (ImageSwitcher) findViewById(R.id.is);
// 设置工厂
mis.setFactory(this);
// 设置图片资源 默认显示的是数组中第0张图片
mis.setImageResource(imageIds[position]);
}
// 复写制造图片方法,返回一个新的图片
@Override
public View makeView() {
return new ImageView(this);
}
public void click(View view) {
switch (view.getId()) {
case R.id.next:
position++;
if (position == imageIds.length) {
position = 0;
}
mis.setImageResource(imageIds[position]);
break;
case R.id.up:
position--;
if (position < 0) {
position = imageIds.length - 1;
}
mis.setImageResource(imageIds[position]);
break;
}
}
}
xml布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageSwitcher
android:id="@+id/is"
android:layout_width="match_parent"
android:layout_height="400dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/up"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="click"
android:text="上一张 " />
<Button
android:id="@+id/next"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:onClick="click"
android:text="下一张" />
</LinearLayout>
</LinearLayout>
效果图