編輯:初階開發
這篇筆記整理了一些寫 Android 時反覆用到的基礎片段,適合當速查表。
用 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。
呼叫端(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"));
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 不會對它做資源編解碼處理,適合放純文字資料、音樂或小型資料檔。
setContentView(R.layout.result);
記得先在 XML 中設定 id 屬性,例如 android:id="@+id/result",然後:
TextView resultTv = (TextView) findViewById(R.id.result); searchBtn = (Button) findViewById(R.id.search);
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);
}
}
});
<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;正確做法是用非同步任務或背景線程處理,完成後再回到主線程更新介面。
iOS 與 Android 之爭:從開放與封閉系統看平台勝負
開放與封閉的辯證 近來智慧型手機平台的競爭,常被簡化為開放與封閉之爭。有人認為 iOS 以一致的使用者體驗取勝,也有人相信 Android 的開放生態能帶來更多應用與內
Android 美觀 ListView 表格:水平捲動與自訂底色
用 ListView 做出表格效果這個範例以 ListView 呈現多欄資料,並加入水平捲動與自訂底色,讓列表更像表格。核心做法是將 ListView 放進 Horizo
Android 調試技巧:Eclipse 行號顯示與 Logcat 錯誤定位
很多剛入門 Android 的開發者,常會遭遇 Force Close 或 ANR 這類問題。通常我們可以透過 Android 系統的錯誤日誌工具 Logcat 查看出錯
HTC Hero 玩家自製 ROM:把 Android 2.1 裝進 Hero
HTC Hero 是一款硬體配置相當堅實的智慧型手機,對不同版本的 Android 系統展現出不錯的相容性。先前就曾有用戶把 HTC 新機 Espresso 內建的 An