Android ImageView实现上一页,下一页图片切换

刚开始学习Android真的是头很大,需要学习和理解的东西太多,还好网上可以四处搜索加强自己的理解和学习,多的不说上图片上代码。

实际效果是这样的:
在这里插入图片描述
在这里插入图片描述
布局文件:

activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity">

    <TextView
     
  • 5
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的AS程序实现一页和下一页图片轮播切换显示的示例代码: ```java import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.ImageView; public class MainActivity extends AppCompatActivity { private int[] imageIds = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4}; private int currentIndex = 0; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = findViewById(R.id.imageView); imageView.setImageResource(imageIds[currentIndex]); } public void previousImage(View view) { if (currentIndex == 0) { currentIndex = imageIds.length - 1; } else { currentIndex--; } imageView.setImageResource(imageIds[currentIndex]); } public void nextImage(View view) { if (currentIndex == imageIds.length - 1) { currentIndex = 0; } else { currentIndex++; } imageView.setImageResource(imageIds[currentIndex]); } } ``` 在这个程序中,我们定义了一个数组来存储所有需要显示的图片资源ID,以及一个变量来记录当前显示的图片的索引。在程序启动时,我们将当前索引对应的图片显示在ImageView中。 当用户点击"上一页"按钮时,我们将当前索引减1,并显示对应的图片。如果当前已经是第一图片,则显示最后一图片。 当用户点击"下一页"按钮时,我们将当前索引加1,并显示对应的图片。如果当前已经是最后一图片,则显示第一图片。 我们可以在布局文件中添加两个按钮来触发上一页和下一页的操作: ```xml <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center_horizontal"> <Button android:id="@+id/previousButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上一页" android:onClick="previousImage"/> <Button android:id="@+id/nextButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="下一页" android:onClick="nextImage"/> </LinearLayout> ``` 注意到我们为这两个按钮设置了onClick属性,分别对应调用MainActivity中的previousImage和nextImage方法。这样,当用户点击按钮时,程序就会调用对应的方法来切换显示图片。 这个程序只是一个简单的例子,实际上图片轮播切换显示还有很多细节需要考虑,例如图片的加载和缓存、图片切换的动画效果等等。但是这个例子可以帮助我们理解如何通过代码来实现图片轮播的基本功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值