2015年12月18日 星期五

Android - Ch4 第一支 Android 程式:婚姻建議程式

 

Android Studio 的介面還算整齊好用,有分圖形介面(Design mode)和程式碼介面(Text mode),以左下角按鈕切換。本例照操作的順序總共用到三個檔案:

  • 介面布局檔 : content_main.xml
  • 活動程式檔 : MainActivity.java
  • 字串資源檔 : string.xml



一、編輯介面布局檔 : content_main.xml


「介面佈局檔」是用樹狀結構的方式來組織程式畫面中的介面元件,它是一個XML格式的檔案,每一個標籤都是一個介面元件,像是<Button … />,標籤裡頭是介面元件的屬性設定。Android SDK提供非常豐富的介面元件,讓程式開發人員可以做出各種生動有趣的操作畫面,如果能夠進一步搭配相關的程式資源,像是Nine-Patch影像檔、State List、Shape、Theme和Style,更可以打造出屬於自己風格的程式畫面。

  1. 把 RelativeLayout 改成 LinearLayout 並設成 vertical mode
  2. 把 TextView、EditText、Spinner、Button 等介面元件加一加,記得元件上面的文字要用new string value產生,這樣元件上面的字串可以在res/values/string.xml這個檔案統一管理,更好維護!


content_main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main" tools:context=".MainActivity"
    android:orientation="vertical"
    android:weightSum="1">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_age"
        android:id="@+id/str_age"
        android:layout_alignParentStart="true"
        android:textSize="@dimen/abc_text_size_display_1_material" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/edt_age"
        android:hint="@string/edt_age"
        android:textSize="@dimen/abc_text_size_headline_material"
        android:layout_below="@+id/str_age"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_sex"
        android:id="@+id/str_sex"
        android:textSize="@dimen/abc_text_size_display_1_material"
        android:layout_below="@+id/edt_age"
        android:layout_alignEnd="@+id/str_age"
        android:layout_gravity="center_vertical" />

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/spn_sex"
        android:entries="@array/sex_list"
        android:spinnerMode="dialog"
        android:prompt="@string/spn_sex_list_prompt"
        android:layout_below="@+id/str_sex"
        android:layout_alignParentStart="true"
        android:layout_weight="0.18" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/btn_ok"
        android:id="@+id/btn_ok"
        android:textSize="@dimen/abc_text_size_display_1_material"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_suggest"
        android:id="@+id/str_suggest"
        android:textSize="@dimen/abc_text_size_display_1_material"
        android:layout_below="@+id/btn_ok"
        android:layout_alignParentStart="true"
        android:layout_marginTop="46dp" />


</LinearLayout>





二、查看字串資源檔 : string.xml


本例可以不用在這編輯,不過剛剛new string value產生的字串都可以在這查看修改。

string.xml


<resources>
    <string name="app_name">Opengate App : Marriage Suggestion System</string>
    <string name="action_settings">Settings</string>

    <!-- for main list -->
    <string name="str_sex">Sex</string>
    <string name="str_age">Age</string>
    <string name="str_suggest">Suggestion:</string>
    <string name="edt_sex">(Input your sex)</string>
    <string name="edt_age">(Input your age)</string>
    <string name="btn_ok">OK</string>

    <!-- for suggestion option -->
    <string name="sug_not_hurry">not hurry</string>
    <string name="sug_get_married">loser! get married quickly!</string>
    <string name="sug_find_couple">find couple now : )</string>

    <!-- for spinner -->
    <string-array name="sex_list">
        <item>Male</item>
        <item>Female</item>
    </string-array>
    <string name="spn_sex_list_prompt">Please choose your sex</string>

    <!-- for sex check -->
    <string name="sex_male">male</string>

</resources>






三、編輯活動程式檔 : MainActivity.java


本次撰寫的java程式碼大概有以下功能

  1. 用findViewById()找到對應的介面元件
  2. 用一個View.OnClickListener設給Button物件,這樣按下按鈕就會執行 (spinner的AdapterView.OnItemSelectedListener也是同理)

MainActivity.java


package com.example.opengate.lesson_bmi;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /* declaration  START */

    private EditText edt_age;
    private TextView str_suggest;
    private Button btn_ok;
    private Spinner spn_sex;
    private String ms_sex;

    /* declaration  END */

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        /* variable initialization START */

        edt_age = (EditText) findViewById(R.id.edt_age);
        btn_ok = (Button) findViewById(R.id.btn_ok);
        str_suggest = (TextView) findViewById(R.id.str_suggest);

        btn_ok.setOnClickListener(btnOKonClick);

        spn_sex = (Spinner) findViewById(R.id.spn_sex);
        spn_sex.setOnItemSelectedListener(spnSexOnItemSelected);

        /* variable initialization END */
    }


    /* for spinner check START */
    private AdapterView.OnItemSelectedListener spnSexOnItemSelected = new AdapterView.OnItemSelectedListener(){

        public void onItemSelected(AdapterView parent, View v, int position, long id){
            ms_sex = parent.getSelectedItem().toString();
        }

        public  void onNothingSelected(AdapterView parent){
        }
    };
    /* for spinner check END */


    /* action when click the btn START*/
    private View.OnClickListener btnOKonClick = new View.OnClickListener(){
        @Override
        public void onClick(View v) {

            int age = Integer.parseInt(edt_age.getText().toString());

            String suggest = getString(R.string.str_suggest);

            if(ms_sex.equals(getString(R.string.sex_male)))
                if(age < 30)
                    suggest += getString(R.string.sug_not_hurry);
                else if(age > 35)
                    suggest += getString(R.string.sug_get_married);
                else
                    suggest += getString(R.string.sug_find_couple);
            else
                if(age < 25)
                    suggest += getString(R.string.sug_not_hurry);
                else if(age > 30)
                    suggest += getString(R.string.sug_get_married);
                else
                    suggest += getString(R.string.sug_find_couple);

            str_suggest.setText(suggest);
        }
    };
    /* action when click the btn END*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}




四、歡樂的小小DEMO時光


可以從這第一支婚姻建議的Android程式中了解到一些基本概念,不過這功能還真是陽春到無法直視阿XD 






References


書籍:Android 程式設計入門、應用到精通






技術提供:Blogger.