2013年9月7日 星期六

基本入門(2) - Android 新手學習筆記

本篇記錄一些常用到的設定或語法

有時Eclipse要執行專案時會出現以下的錯誤
在 Android Device Chooser 中,Device 的 Target 版本顯示 Unknown
解決:將手持裝置的傳輸線拔起來重插,大部份時候即可解決

The connection to adb is down, and a severe error has occured
解決:
(1)重啟Eclipse可以解決
(2)有人說必須依下步驟解決(每次發生就這麼處理,無法一勞永逸)
1. 先關閉Eclipse
2. 開啟命令視窗,切換到 Android SDK platform-tools 資料夾
3. 執行  adb kill-server
4. 再執行 adb start-server
5. 如果沒有錯誤發生,則可以開啟 Eclipse 來用了

預設安裝在SDCard
在 AndroidManifest.xml,Manifest頁籤的 Install location 選 preferExternal
應該也要配合在Permissions頁籤加入權限
Uses-Permission : android.permission.WRITE_EXTERNAL_STORAGE

固定螢幕的方向
在 AndroidManifest.xml,Application頁籤,點選要設定的Activity,
然後在右方的 Screen orientation 選擇要的方向
landscape:橫式
portrait:直式

以比例來設元件的寬高
沒有%的單位,但可以在排版檔用 layout_weight 來設定所佔比例

設文字的對齊
android:gravity,注意不是LayoutParams中的gravity

設定文字的顏色
(1)在排版檔中,設定 Text Color 屬性值,用 #RRGGBB 格式
(2)在 code 中,呼叫元件的 setTextColor(Color.RED);
註:此Color為 android.graphics.Color

設定文字的大小
(1)在排版檔中,設定 Text Size 屬性值,一般會用 sp 及 dp 兩種單位,例如 10sp
(2)在 code 中,呼叫元件的 setTextSize(float size) 或是 setTextSize(int unit, float size)
前者的單位應該是 sp,後者則可自己指定單位
單位值為 TypedValue.COMPLEX_UNIT_? (不確定是否全部都能用)

這文字單位真是不好搞
官網說明:
A dp is a density-independent pixel that corresponds to the physical size of a pixel at 160 dpi. An sp is the same base unit, but is scaled by the user's preferred text size (it’s a scale-independent pixel), so you should use this measurement unit when defining text size

取得某個元件
(即View,每個元件都是繼承View來的)
在排版檔(xml),ID屬性設為 @+id/myView
在 Activity 中
View myView = this.findViewById(R.id.myView);

設定元件顯示或隱藏
view.setVisibility(View.VISIBLE); //顯示
view.setVisibility(View.GONE); //隱藏 (消失,不佔UI空間)
view.setVisibility(View.INVISIBLE); //隱藏  (不可見,但仍佔有UI空間)

設定事件(以onClick為例)
(1)
在 Activity 中宣告一個 method
public void xxx(View view){
//do something
}
然後在排版檔該元件的onClick屬性設為 xxx (即上述 method 的名稱)即可
(2)
實作一個 listener 類別
public class MyListener implements View.OnClickListener {
@Override
public void onClick(View view){
//do something
}
}
然後呼叫元件的 setOnClickListener(new MyListener());

設成全螢幕
在Activity中getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

不要顯示標題列
在Activity中requestWindowFeature(Window.FEATURE_NO_TITLE);

取得螢幕資訊
在Activity中
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
//"螢幕解析度(px)為 "+metrics.widthPixels+" x "+metrics.heightPixels);
//"螢幕dpi為 "+metrics.xdpi+" x "+metrics.ydpi);
註1:
只有Context時,取WindowManager的語法
WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
註2:
dp = px * 160 / dpi
px = dp * (dpi / 160)

使用Timer
這裡有三種方法
參考 http://stackoverflow.com/questions/4597690/android-timer-how
另外,若要倒數計時,則可以用 CountDownTimer

沒有留言:

張貼留言

廣告訊息會被我刪除

Related Posts with Thumbnails