Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發常用程式碼片段整理

編輯:關於 Android 程式設計

在日常的 Android 開發過程中,總有一些高頻使用卻又容易忘記的程式碼片段。把它們系統性地整理下來,不僅能提升編碼效率,也能在關鍵時刻省去反覆查資料的麻煩。以下就針對幾個常見場景,示範最典型的寫法。

一、取得 RadioButton 的選中狀態

單選按鈕的狀態判斷非常基礎,透過 findViewById 綁定元件後,再呼叫 isChecked() 即可得知是否被選中:

rb1 = (RadioButton)findViewById(R.id.sex1);
if (rb1.isChecked())
{
    sex = "M";
} else
{
    sex = "F";
}

二、兩個 Activity 之間傳遞資料

頁面跳轉時常需要帶上一批參數,最直觀的做法是透過 Intent 搭配 Bundle 完成。

發送方:

Intent intent = new Intent();
intent.setClass(EX03_11.this, EX03_11_1.class);

Bundle bundle = new Bundle();
bundle.putDouble("height", height);
bundle.putString("sex", sex);
intent.putExtras(bundle);

// 打開另一個 activity
startActivityForResult(intent, 0);

接收方:

intent = this.getIntent();
bundle = intent.getExtras();
String sex = bundle.getString("sex");
double height = bundle.getDouble("height");

三、彈出一個訊息對話框

使用 AlertDialog.Builder 可以輕鬆建立帶有標題、內容與按鈕的提示視窗:

new AlertDialog.Builder(EX03_12.this)
   .setTitle(R.string.app_about)
   .setMessage(R.string.app_about_msg)
   .setPositiveButton(R.string.str_ok,
       new DialogInterface.OnClickListener()
       {
           public void onClick(DialogInterface dialoginterface, int i)
           {
           }
       }).show();

四、變更文字方塊的字型

若想讓介面呈現特殊的字體風格,可以先將字型檔放進 assets 目錄,再透過 Typeface 載入:

mText.setTypeface(Typeface.createFromAsset(getAssets(),
    "fonts/HandmadeTypewriter.ttf"));

提醒:需在 assets 目錄下建立 fonts 資料夾,並放入 HandmadeTypewriter.ttf 字型檔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved