<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_horizontal"> <!-- 定义一个GridView组件 --> <GridView android:id="@+id/grid01" android:layout_width="match_parent" android:layout_height="wrap_content" android:horizontalSpacing="2dp" android:verticalSpacing="2dp" android:numColumns="4" android:gravity="center"/> <!-- 定义一个ImageSwitcher组件 --> <ImageSwitcher android:id="@+id/switcher" android:layout_width="300dp" android:layout_height="300dp" android:layout_gravity="center_horizontal" android:inAnimation="@android:anim/fade_in" android:outAnimation="@android:anim/fade_out"/> </LinearLayout>主界面
package com.example.viewswitcher import android.app.Activity import android.os.Bundle import android.view.View import android.view.ViewGroup.LayoutParams import android.widget.* import android.widget.ViewSwitcher.ViewFactory import android.widget.AdapterView.OnItemClickListener import android.widget.AdapterView.OnItemSelectedListener class MainActivity : Activity() { internal var imageIds = intArrayOf(R.drawable.bomb5, R.drawable.bomb6, R.drawable.bomb7, R.drawable.bomb8, R.drawable.bomb9, R.drawable.bomb10, R.drawable.bomb11, R.drawable.bomb12, R.drawable.bomb13, R.drawable.bomb14, R.drawable.bomb15, R.drawable.bomb16) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 创建一个List对象,List对象的元素是Map val listItems = ArrayList<Map<String, Any>>() for (i in imageIds.indices) { val listItem = HashMap<String, Any>() listItem["image"] = imageIds[i] listItems.add(listItem) } // 获取显示图片的ImageSwitcher val switcher = findViewById<ImageSwitcher>(R.id.switcher) // 为ImageSwitcher设置图片切换的动画效果 // 使用Lambda表达式创建ViewFactory,表达式是makeView方法()的方法体 switcher.setFactory { // 创建ImageView对象 val imageView = ImageView(this@MainActivity) imageView.scaleType = ImageView.ScaleType.FIT_CENTER imageView.layoutParams = FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) // 返回ImageView对象 imageView } // 创建一个SimpleAdapter val simpleAdapter = SimpleAdapter(this, listItems, R.layout.cell, arrayOf("image"), intArrayOf(R.id.image1)) // 使用/layout/cell.xml文件作为界面布局 val grid = findViewById<GridView>(R.id.grid01) // 为GridView设置Adapter grid.adapter = simpleAdapter // 添加列表项被选中的监听器 grid.onItemSelectedListener = object : OnItemSelectedListener { override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) { // 显示当前被选中的图片 switcher.setImageResource(imageIds[position]) } override fun onNothingSelected(parent: AdapterView<*>) { } } // 添加列表项被单击的监听器 grid.setOnItemClickListener {parent, view, position, id -> // 显示被单击的图片 switcher.setImageResource(imageIds[position]) } } }主程序