3分钟
2.1.3 实施步骤
实施步骤
步骤1:新建一个Module,命名为Ex2_1_3,其他设置默认。
步骤2:打开Ex2_1_3/res/drawable目录,将cloth.png,play.png,scissors.png,stone.png等图片资源拷贝到这里。如图2-1-3-2所示。需要注意的是,放到资源目录下的资源文件名必须由小写英文字母以及下划线构成。
步骤3:修改Ex2_1_3/values/strings.xml文件,清单如下。
表2-1-8 Ex2_1_3 strings.xml清单
<resources>
<string name="app_name">猜拳游戏</string>
<string name="title">石头剪刀布游戏,左边是电脑,右边是玩家</string>
</resources>
步骤4:在activity_main.xml布局文件上添加控件,并设定相应属性,完成的清单如下。
表2-1-9 Ex2_1_3 activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="@string/title"
android:textSize="32sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:id="@+id/ivComputer"
android:layout_width="128dp"
android:layout_height="128dp"
app:srcCompat="@drawable/cloth" />
<ImageView
android:id="@+id/ivPlayer"
android:layout_width="128dp"
android:layout_height="128dp"
app:srcCompat="@drawable/scissors" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<ImageButton
android:id="@+id/iBtnPlay"
android:layout_width="256dp"
android:layout_height="128dp"
android:onClick="btnPlayGame"
android:scaleType="fitXY"
app:srcCompat="@drawable/play" />
</LinearLayout>
</LinearLayout>
步骤5:修改MainActivity.java文件中的MainActivity类内容,代码清单如下。
表2-1-10 MainActivity.javaMainActivity
public class MainActivity extends AppCompatActivity {
//用于表示图片
int[] images = {R.drawable.stone, R.drawable.scissors, R.drawable.cloth};
//用于指向控件
ImageView ivComputer, ivPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ivComputer = (ImageView) findViewById(R.id.ivComputer);
ivPlayer = (ImageView) findViewById(R.id.ivPlayer);
}
public void btnPlayGame(View v) {
Random r = new Random();
int iComputer = r.nextInt(3);
int iPlayer = r.nextInt(3);
ivComputer.setImageResource(images[iComputer]);
ivPlayer.setImageResource(images[iPlayer]);
}
}
学员评价