本文实例讲述了Android开发实现的图片点击切换功能。分享给大家供大家参考,具体如下:
java 代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
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 文件
1
2
3
4
5
6
7
8
9
10
11
|
<? 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程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_43377749/article/details/83661958