说明:通过ImageView控件显示图片资源,点击Button控件实现对图片的切换。
创建一个新的Android项目,添加图片资源到drawable资源文件夹cute1.jpg
cute2.jpg
cute3.jpg
cute4.jpg
cute5.jpg
cute6.jpg在布局文件中添加一个ImageView和两个Button,作为主界面
效果:
在Activity文件中编写切换图片和显示图片的代码
private Button lastPhoto;private Button nextPhoto;private ImageView displayPhoto;//存储图片资源的数组private int[] photos = {R.drawable.cute1, R.drawable.cute2, R.drawable.cute3, R.drawable.cute4, R.drawable.cute5, R.drawable.cute6};//显示当前图片的索引private int photoIndex = 0;//图片索引最大值(图片数-1)private int maxIndex = 5;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//初始化init();}/*** 控件初始化*/private void init() {lastPhoto = findViewById(R.id.lastPhoto);lastPhoto.setOnClickListener(this);nextPhoto = findViewById(R.id.nextPhoto);nextPhoto.setOnClickListener(this);displayPhoto = findViewById(R.id.displayPhoto);}@Overridepublic void onClick(View view) {switch (view.getId()) {case R.id.lastPhoto://如果当前图片是第一张,则上一张图片为最后一张图片if (photoIndex == 0) {photoIndex = maxIndex;} else {//否则改为上一张图片索引photoIndex = photoIndex - 1;}break;case R.id.nextPhoto://如果当前图片是最后一张,则下一张图片为第一张图片if (photoIndex == maxIndex) {photoIndex = 0;} else {//否则改为下一张图片索引photoIndex = photoIndex + 1;}break;default:break;}//显示图片displayPhoto.setImageResource(photos[photoIndex]);}
注意:在AndroidManifest.xml文件中设置以下属性
android:hardwareAccelerated="false"android:largeHeap="true"
程序运行结果:
源码:点击下载
PS:今天是中秋节,祝大家中秋节快乐!珍惜和家人在一起的时光!