天天看點

第一個APP——GeoQuiz

第一個APP的知識點以及對代碼的了解

APP預覽

首頁面效果圖

第一個APP——GeoQuiz

首先要做的就是界面設計

activity_quiz.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" />
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/true_button"/>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/false_button"/>

    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/prev_button"/>
        <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/next_button"/>

    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|center_horizontal"
        android:text="@string/cheat_button"/>

</LinearLayout>      

元件是使用者界面的構造子產品。元件可以顯示文字或圖像,與使用者互動,甚至布置螢幕上的其他元件。按鈕、文本輸入控件和選擇框等都是元件。

上圖共含有如下幾個元件:

一個垂直LinearLayout元件; 一個TextView元件; 三個個水準LinearLayout元件; 五個個Button元件。

建立字元串資源

字元串資源包含在一個獨立的名為strings的XML檔案中,需要在activity_quiz.xml檔案中引用的字元串資源目前還不存在。現在我們來添加這些資源。 strings.xml

<resources>
    <string name="app_name">GeoQuiz</string>
    <string name="question_australia">堪培拉是澳洲的首都 </string>
    <string name="true_button">TRUE</string>
    <string name="false_button">FALSE</string>
    <string name="prev_button">Prev</string>
    <string name="cheat_button">Cheat!</string>
</resources>      

現在,在GeoQuiz項目的任何XML檔案中,隻要引用到@string/false_button,應用運作時,就會得到文本“FALSE”

資源ID

要想對元件進行操作,首先要為元件生成資源ID,在activity_quiz.xml檔案中,為按鈕添加上android:id屬性 為按鈕添加資源ID(activity_quiz.xml),如:true button

android:id="@+id/true_button"      

設定完id之後就可以在QuizActivity中直接擷取它們

添加成員變量(QuizActivity.java)

private Button mTrueButton;      

如果出現報錯可能是因為沒有導入包,按Alt+Enter組合鍵可以自動導入所需要的包

 引用元件(QuizActivity.java)

添加完成員變量後就要開始引用

mTrueButton = (Button) findViewById(R.id.true_button);      

設定監聽器

監聽器是實作特定監聽器接口的對象,用來監聽某類事件的發生。 目前應用需要監聽使用者的按鈕單擊事件,是以監聽器需實作View.OnClickListener接口。

mTrueButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
          
            }
 });      

當按鈕mTrueButton被點選後,監聽器會立即通知我們。傳入setOnClickListener(OnClickListener)方法的參數是一個監聽器。 該參數是一個實作了OnClickListener接口的對象。

建立提示消息

接下來要實作的就是,單擊true按鈕,彈出我們稱為toast的提示消息。Android的toast是用來通知使用者的簡短彈出消息。 首先完善string.xml

<string name="correct_toast">Correct!</string>
  <string name="incorrect_toast">Incorrect!</string>      

使用代碼自動補全,選擇makeText(Context context, int resID, int duration)方法,完成makeText方法的全部參數設定

mTrueButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                Toast.makeText(QuizActivity.this,R.string.incorrect_toast,Toast.LENGTH_SHORT).show();
               
            }
   });      

 為了完善APP,增加題庫,所有還需要為項目建立一個Question類,該類的一個執行個體代表一個問題,

然後再建立一個Question數組對象交由QuizActivity管理 Question.java

public class Question {
    private int mTextResId;
    private boolean mAnswerTrue;

    public Question(int textResId,boolean answertrue){
        mTextResId = textResId;
        mAnswerTrue = answertrue;
    }

    public int getTextResId() {
        return mTextResId;
    }

    public void setTextResId(int textResId) {
        mTextResId = textResId;
    }

    public boolean isAnswerTrue() {
        return mAnswerTrue;
    }

    public void setAnswerTrue(boolean answerTrue) {
        mAnswerTrue = answerTrue;
    }
}      

Question類中封裝的資料有兩部分:問題文本和問題答案(true或false) 變量mTextResId用來儲存地理知識問題字元串的資源ID。資源ID總是int類型,是以這裡設定它為int而不是String類型

新增按鈕以及文本視圖的調整(activity_quiz.xml)

<TextView
        android:id="@+id/question_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="24dp" />      
<Button
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/next_button"/>      

更新字元串資源定義(strings.xml)

<string name="next_button">Next</string>      

添加問題庫

<string name="question_oceans">太平洋比大西洋大</string>
    <string name="question_mideast">蘇伊士運河連接配接着紅海和印度洋</string>
    <string name="question_africa">尼羅河流域在埃及</string>
    <string name="question_americas">亞馬遜河是美國最長的河</string>
    <string name="question_asia">貝加爾湖是世界上最古老最深的淡水湖</string>      

 下面要在QuizActivity.java檔案中添加TextView和新Button變量。另外,再建立一個Question對象數組以及一個該數組的索引變量

增加按鈕變量及Question對象數組(QuizActivity.java)

private Button mNextButton;
private TextView mQuestionTextView;
private Question[] mQuestionBank = new Question[]{
            new Question(R.string.question_australia ,true),
            new Question(R.string.question_oceans,true),
            new Question(R.string.question_mideast,false),
            new Question(R.string.question_africa,false),
            new Question(R.string.question_americas,true),
            new Question(R.string.question_asia,true)
    };

 private int mCurrentIndex=0;      

引用TextView,并将其文本内容設定為目前數組索引所指向的地理知識問題

使用TextView(QuizActivity.java)

mQuestionTextView = (TextView) findViewById(R.id.question_text_view);
int question = mQuestionBank[mCurrentIndex].getTextResId();
mQuestionTextView.setText(question);
      

然後運作GeoQuiz應用。可看到數組存儲的第一個問題顯示在TextView上了

為Next按鈕設定監聽器

該監聽器的作用是:遞增數組索引并相應更新顯示TextView的文本内容

mNextButton = (Button) findViewById(R.id.next_button);
mNextButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;
    int question = mQuestionBank[mCurrentIndex].getTextResId();
    mQuestionTextView.setText(question);
    }
});      
mCurrentIndex = (mCurrentIndex + 1) % mQuestionBank.length;這段代碼表示向下切換,
是以在挑戰練習中增加向上切換隻需要把+1改成-1即可
      

使用updateQuestion()封裝公共代碼(QuizActivity.java)

private void updateQuestion(){
        int question = mQuestionBank[mCurrentIndex].getTextResId();
        mQuestionTextView.setText(question);
    }      

封裝代碼的隻要目的是減少重複代碼,可以直接調用

mNextButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                mCurrentIndex = (mCurrentIndex+1) % mQuestionBank.length;
                updateQuestion();
            }
        });      

增加方法checkAnswer(boolean)(QuizActivity.java)

private void checkAnswer(boolean userPressedTrue){
        boolean answerIsTrue = mQuestionBank[mCurrentIndex].isAnswerTrue();
        int messageResId = 0;
        if(mIsCheater){
            messageResId = R.string.judgment_toast;
        }else {
            if (userPressedTrue == answerIsTrue)
            {
                messageResId = R.string.correct_toast;
            } else {
                messageResId = R.string.incorrect_toast;
            }
        }
        Toast.makeText(this,messageResId,Toast.LENGTH_SHORT).show();
    }      

private void checkAnswer(boolean userPressedTrue)該方法接受boolean類型的變量參數,判别使用者單擊了TRUE還是FAL S E按鈕。 然後,将使用者的答案同目前Question對象中的答案作比較。最後,判斷答案正确與否,生成一個Toast消息回報給使用者。

調用方法checkAnswer(boolean)(QuizActivity.java)

在按鈕的監聽器裡,調用checkAnswer(boolean)方法

mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener(){
            public void onClick(View v){
                //Toast.makeText(QuizActivity.this,R.string.incorrect_toast,Toast.LENGTH_SHORT).show();
                checkAnswer(true);
            }
        });      

為按鈕添加圖示,需要在XML檔案中引用資源

<Button     
android:id="@+id/next_button"     
android:layout_width="wrap_content"     
android:layout_height="wrap_content"     
android:text="@string/next_button"     
android:drawableRight="@drawable/arrow_right"     
android:drawablePadding="4dp" 
/>      

日志跟蹤了解Activity生命周期

輸出日志資訊

Android的android.util.Log類能夠發送日志資訊到系統級别的共享日志中心。Log類有好幾個日志記錄方法。本書使用最多的是以下方法:public static int d(String tag, String msg), d代表着“debug”的意思,用來表示日志資訊的級别。第一個參數表示日志的來源,第二個參數表示日志的具體内容。該方法的第一個參數通常以類名為值的TAG常量傳入。這樣,很容易看出日志資訊的來源。

新增一個TAG常量(QuizActivity.java)

private static final String TAG = "QuizActivity";      

為onCreate(...)方法添加日志輸出代碼(QuizActivity.java)

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"onCreate(Bundle)called");
        setContentView(R.layout.activity_quiz);      

覆寫更多生命周期方法(QuizActivity.java)

@Override
    public void onStart(){
        super.onStart();
        Log.d(TAG,"onStart() called");
    }
    @Override
    public void onResume(){
        super.onResume();
        Log.d(TAG,"onResume() called");
    }
    @Override
    public void onPause(){
        super.onPause();
        Log.d(TAG,"onPause() called");
    }
 @Override
    public void onStop(){
        super.onStop();
        Log.d(TAG,"onStop() called");
    }
    @Override
    public void onDestroy(){
        super.onDestroy();
        Log.d(TAG,"onDestroy() called");
    }      

建立CheatActivity,實作界面跳轉

一個activity啟動另一個activity最簡單的方式是使用以下startActivity方法: public void startActivity(Intent intent)

基于intent的通信

intent對象是component用來與作業系統通信的一種媒介工具 在GeoQuiz應用中,intent用來告訴ActivityManager該啟動哪個activity,是以可使用以下構造方法: public Intent(Context packageContext, Class<?> cls) 傳入該方法的Class類型參數告訴ActivityManager應該啟動哪個activity; Context參數告訴ActivityManager在哪裡可以找到它

啟動CheatActivity(QuizActivity.java)

在mCheatButton的監聽器代碼中,建立包含CheatActivity類的Intent執行個體,然後将其傳入startActivity(Intent)方法

mCheatButton = (Button)findViewById(R.id.cheat_button); 
mCheatButton.setOnClickListener(new View.OnClickListener() {    
 @Override   
      public void onClick(View v) {        
            Intent i = new Intent(QuizActivity.this, CheatActivity.class); 
            startActivity(i);    
       } 
})                  

轉載于:https://www.cnblogs.com/mhhs/p/7525480.html