700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Android实现简单的上一张 下一张图片切换显示

Android实现简单的上一张 下一张图片切换显示

时间:2023-06-11 02:36:40

相关推荐

Android实现简单的上一张 下一张图片切换显示

说明:通过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:今天是中秋节,祝大家中秋节快乐!珍惜和家人在一起的时光!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。