@Override
public void onClick(View v) {
//显示消息提示框
Toast.makeText(MainActivity.this, "进入游戏...", Toast.LENGTH_SHORT).show();
}
});
运行本实例,将显示如图3.32所示的运行结果。
图3.32 我同意游戏条款的效果
3.4.2 猜猜鸡蛋放在哪只鞋子里
例3.26 在Eclipse中创建Android项目,名称为3.26,实现猜猜鸡蛋放在哪只鞋子里的小游戏。(实例位置:光盘\TM\sl\3\3.26)
(1)修改新建项目的res\layout目录下的布局文件main.xml,将默认添加的垂直线性布局管理器的代码删除,然后添加一个带有3个表格行的TableView布局管理器,其中第1行中添加一个TextView组件,用于显示游戏标题或提示信息;第2行添加一个包含3个ImageView组件的水平线性布局管理器;最后一行添加一个水平线性布局管理器,并且在其中添加一个“再玩一次”按钮。修改后的代码如下:
android:layout_height="match_parent"
android:layout_width="wrap_content"
android:background="@drawable/background"
android:id="@+id/tableLayout1">
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:gravity="center"
android:layout_weight="2">
android:text="@string/title"
android:padding="10px"
android:gravity="center"
android:textSize="35px"
android:textColor="#010D18"
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
android:id="@+id/tableRow2"
android:layout_weight="1"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
android:orientation="horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
android:src="@drawable/shoe_default"
android:paddingLeft="30px"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
…
android:orientation="horizontal"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal">
android:text="再玩一次"
android:id="@+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
(2)在主活动MainActivity中,定义一个保存全部图片id的数组、3个ImageView类型的对象和一个TextView类型的对象,具体代码如下:
int[] imageIds = new int[] { R.drawable.shoe_ok, R.drawable.shoe_sorry,
R.drawable.shoe_sorry }; //定义一个保存全部图片id的数组
private ImageView image1; //ImageView组件1
private ImageView image2; //ImageView组件2
private ImageView image3; //ImageView组件3
private TextView result; //显示结果
(3)编写一个无返回值的方法reset(),用于随机指定鸡蛋所在的鞋子,关键代码如下:
private void reset() {
for (int i = 0; i < 3; i++) {
int temp = imageIds[i]; //将数组元素i保存到临时变量中
int index = (int) (Math.random() * 2); //生成一个随机数
imageIds[i] = imageIds[index]; //将随机数指定的数组元素的内容赋值给数组元素i
imageIds[index] = temp; //将临时变量的值赋值给随机数组指定的数组元素
}
}
(4)由于ImageButton组件设置背景透明后,将不再显示鼠标单击效果,所以需要通过Drawable资源来设置图片的android:src属性。首先编写一个Drawable资源对应的XML文件button_state.xml,用于设置当鼠标按下时显示的图片以及鼠标没有按下时显示的图片,具体代码如下: