Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 初階開發

Android 學習筆記:七個常用基礎寫法

編輯:初階開發

這篇筆記整理了一些寫 Android 時反覆用到的基礎片段,適合當速查表。

1. 加入捲動效果

用 ScrollView 包住可能超出畫面的內容即可:

<ScrollView
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    >
    <TextView
        android:id="@+id/result"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
    />
</ScrollView>

要注意 ScrollView 只能容納一個直接子元素,若有多個控件需一起捲動,得先包一層 LinearLayout。

2. Activity 之間傳遞資料

呼叫端(aActivity.java):

Intent intent = new Intent();
intent.setClass(SearchActivity.this, ResultActivity.class);
intent.putExtra("value", searchValueEt.getText().toString());
startActivity(intent);

接收端(bActivity.java):

Intent intent = getIntent();
resultTv.setText(intent.getStringExtra("value"));

3. 讀取 res/raw 中的檔案並顯示

InputStream input = this.getResources().openRawResource(R.raw.abc);
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuffer temp = new StringBuffer();
try {
    String s = reader.readLine();
    while (s != null) {
        temp.append(s);
        temp.append("\n");
        s = reader.readLine();
    }
    s = null;
    reader.close();
} catch (IOException e) {
    e.printStackTrace();
}
resultTv.setText(temp.toString());

把文字檔放在 res/raw 的好處是 Android 不會對它做資源編解碼處理,適合放純文字資料、音樂或小型資料檔。

4. 載入 layout 中的內容

setContentView(R.layout.result);

5. 取得 View 中的控件

記得先在 XML 中設定 id 屬性,例如 android:id="@+id/result",然後:

TextView resultTv = (TextView) findViewById(R.id.result);
searchBtn = (Button) findViewById(R.id.search);

6. 加入監聽事件

searchBtn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (v == searchBtn) {
            Intent intent = new Intent();
            intent.setClass(SearchActivity.this, ResultActivity.class);
            intent.putExtra("value", searchValueEt.getText().toString());
            startActivity(intent);
        }
    }
});

7. 在 AndroidManifest.xml 中配置多個 Activity

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".SearchActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity android:name=".ResultActivity"
        android:label="@string/result_name">
    </activity>
</application>

只有掛上 MAIN/LAUNCHER 的那個 Activity 會出現在啟動器;其餘 Activity 只要簡單宣告就能被 Intent 啟動。

補充:幾個實務提醒

讀取檔案的範例中,BufferedReader 與 InputStream 都應該在 finally 區塊或 try-with-resources 中關閉,避免檔案描述符洩漏。另外,檔案讀寫與網路請求都不該放在 UI 線程執行,較新的 Android 版本會直接拋出 NetworkOnMainThreadException;正確做法是用非同步任務或背景線程處理,完成後再回到主線程更新介面。

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