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

Andriod 開發常見問題整理:版面引用、版本判斷、螢幕旋轉與型別轉換

編輯:關於 Android 程式設計

本文把 Android 開發過程中經常卡住的小問題整理成清單,每一項都附上可直接複製的寫法。

1. 版面檔中引用另一個版面

用 <include> 標籤即可,把重複的區塊抽成獨立檔案再引入,能有效減少重複定義、讓結構更清楚:

<LinearLayout>
    <include layout="@layout/buttom">
</LinearLayout>

2. 判斷系統版本是否在 4.0 以上

if (android.os.Build.VERSION.SDK_INT > 10) {
    // 4.0 以上的處理
}

3. 螢幕旋轉與 Activity 被重建

在需要的 Activity 上加上這兩行:

android:screenOrientation="portrait"          // 鎖定直向顯示
android:configChanges="keyboardHidden|orientation"  // 旋轉時不重建 Activity

第二行的意思是把 orientation 變更交給系統自行重繪,而不是走一次完整的生命週期重建流程。

4. 移除 App 頂部的標題列

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

這行必須放在 super.onCreate(savedInstanceState); 之前,否則會無效。

5. 跳到手機系統設定畫面

Intent mIntent = new Intent();
ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
mIntent.setComponent(comp);
mIntent.setAction("android.intent.action.VIEW");
startActivity(mIntent);

把 ComponentName 換成其他 Settings 內的 Activity,就能跳到對應的設定頁。

6. Eclipse 中引入第三方專案

在目前的專案上按右鍵 → Properties → Android,點 Add 按鈕把要參照的專案加入,再按 Apply 即可。

7. int 與 String 的互相轉換

String.valueOf(intValue);      // int 轉 String
Integer.parseInt(strValue);    // String 轉 int

第二種寫法要注意:字串若為 null 或非數字內容會丟出例外,正式環境記得包上 try-catch 或先檢查。

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