step1:記分器簡介
這是一個(gè)可以記錄籃球賽中比賽雙方成績的應(yīng)用,得分分為兩分球郑诺、三分球夹姥、罰球(一分),比賽結(jié)束后可以重置辙诞。最終效果如圖所示:
step2:創(chuàng)建工程項(xiàng)目
小弟用的是Android Studio,API15辙售,空模版。
緊接著是三部曲:
1.選擇所用view和數(shù)量:
顯而易見飞涂,兩個(gè)TextView,三個(gè)Button旦部。
2.選擇position views:
因?yàn)槭且粋€(gè)簡單的垂直布局,所以選擇LinearLayout線性布局封拧。
3.style of views:
TextView要居中顯示志鹃,三個(gè)按鈕都要在水平方向占滿整個(gè)視圖。還有合適的內(nèi)邊距(padding:4dp)和外邊距(layout_margin:8dp),你也可以選擇自己喜歡的方式泽西。
貼上代碼(MainActivity.xml):
<code>
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" tools:context="com.example.administrator.countcounter.MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Team A"
android:gravity="center_horizontal"
android:padding="4dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:gravity="center_horizontal"
android:padding="4dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="+2point"
android:layout_margin="8dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="+3point"
android:layout_margin="8dp"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="free goal"
android:layout_margin="8dp"/>
</LinearLayout>
</code>
使文本居中的方法是添加屬性<code>android:gravity="center_horizontal"</code>
這個(gè)屬性還有垂直居中(center_vertical)曹铃、居中(center)等。如果你發(fā)現(xiàn)文本沒有居中可能是你的TextView的寬度不夠大捧杉。
這時(shí)盡管你的設(shè)置居中了陕见,但它是針對于藍(lán)色框的寬度居中。
這樣才是對的味抖。
step3創(chuàng)建方法
現(xiàn)在评甜,按鈕并不會(huì)做任何事情,我們需要將xml文件與java文件關(guān)聯(lián)起來仔涩。
在MainActivity.java文件中MainActivity方法中添加一個(gè)新的方法忍坷,代碼如下:
<code>
/**
*Displays the given score for Team A.
*/
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score); scoreView.setText(String.valueOf(score));
}</code>
你同時(shí)需要設(shè)置開啟AutoImport,并將顯示分?jǐn)?shù)的TextView的id改為:team_a_score
<code>android:id="@+id/team_a_score"</code>
現(xiàn)在我們需要一個(gè)全局變量來記錄A隊(duì)的得分,聲明并初始化為0熔脂。
<code>int scoreTeamA = 0;</code>
我們需要為每一個(gè)得分按鈕設(shè)計(jì)方法:
<code>
public void threePointA(View view) {
scoreTeamA = scoreTeamA + 3;
displayForTeamA(scoreTeamA);
}
public void freeGoalA(View view) {
scoreTeamA = scoreTeamA + 1;
displayForTeamA(scoreTeamA);
}
public void twoPointA(View view) {
scoreTeamA = scoreTeamA + 2;
displayForTeamA(scoreTeamA);
}</code>
然后在xml文件中添加調(diào)用:
<code>
android:onClick="threePointA"
android:onClick="twoPointA"
android:onClick="freeGoalA"
</code>
到這里你會(huì)發(fā)現(xiàn)你的應(yīng)用已經(jīng)可以加分了佩研。
時(shí)間有限,先寫到這里霞揉。