Android开发实现的图片点击切换功能示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Android开发实现的图片点击切换功能示例

  2021-04-03 我要评论

本文实例讲述了Android开发实现的图片点击切换功能。分享给大家供大家参考,具体如下:

java 代码

public class MainActivity extends AppCompatActivity {
  //定义一个访问图片的数组
  int[] images = new int[]{
      R.drawable.java,
      R.drawable.javaee,
      R.drawable.swift,
      R.drawable.ajax,
      R.drawable.html,
  };
  //用于图片切换
  int currenImg = 0;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //获取Linearlayout布局容器
    LinearLayout main = (LinearLayout) findViewById(R.id.root);
    //创建ImageView组件
    final ImageView image = new ImageView(this);
    //将ImageView组建添加到linearlayout布局中
    main.addView(image);
    //初始化显示第一张图片
    image.setImageResource(images[0]);
    image.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        image.setImageResource(images[++currenImg % images.length]);
      }
    });
  }
}

xml 文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/root"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  tools:context=".MainActivity">
</LinearLayout>

效果

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们