本次實驗将帶你開發第一個應用,并借此學習一些Android基本概念以及構成應用的UI元件。馬上要開發的應用名叫GeoQuiz,它能給出一道地理知識問題。使用者點選TRUE或FALSE按鈕來回答螢幕上的問題,GeoQuiz即時作出回報。
先進行建立項目
這裡記得選擇Java語言
接下來我們要修改預設元件,先修改activity_main.xml,将下列代碼輸入到activity_main.xml中。
LinearLayout xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“match_parent”
android:layout_height=“match_parent”
android:gravity=“center”
android:orientation=“vertical” >
TextView
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:padding=“24dp”
android:text="@string/question_text" />
LinearLayout
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:orientation=“horizontal” >
Button
android:id="@+id/true_button"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text="@string/true_button" />
Button
android:id="@+id/flase_button"
android:layout_width =“wrap_content”
android:layout_height=“wrap_content”
android:text="@string/false_button" />
/LinearLayout>
/LinearLayout>
然後修改string.xml,将下列代碼輸入到string.xml中
resources>
string name=“app_name”>GeoQuiz
string name=“question_text”>Canberra is the capital of Australia.
string name=“true_button”>True
string name=“false_button”>False
string name=“correct_toast”>Correct!
string name=“incorrect_toast”>Incorrect!
/resources>
最後修改MainActivity.java,将下列代碼輸入到MainActivity.java中
package com.example.genquiz;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button mTrueButton;
private Button mFlaseButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTrueButton = (Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(MainActivity.this,R.string.correct_toast,Toast.LENGTH_SHORT).show();
//Does nothing yet,but soon!
}
});
mFlaseButton = (Button) findViewById(R.id.flase_button);
mFlaseButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast.makeText(MainActivity.this,R.string.incorrect_toast,Toast.LENGTH_SHORT).show();
//Does nothing yet,but soon!
}
});
}
}
最後在模拟機上運作