2013年12月31日

DisplayMetrics

DisplayMetrics (Get the phone screen pixel)


DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int widthPixels = dm.widthPixels;
int heightPixels = dm.heightPixels;

float density = dm.density;
int screenWidth = widthPixels * density ;
int screenHeight = heightPixels * density ;





For example

320*480>
widthPixels is 320, heightPixels is 480, density is 1.0。

480*800>
widthPixels is 320, heightPixels is 533, densityis 1.5。

Android View

自定義view類別
透過class繼承view這個類別

class MainActivityView extends View {
private ShapeDrawable mDrawable;
private Paint mPaint;

public MainActivityView(Context context) {
super(context);
// TODO Auto-generated constructor stub
int height = 100;
int width = 100;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.setBounds(0, 0, width, height);
mPaint = mDrawable.getPaint();
mPaint.setColor(Color.argb(255, 0, 0, 0));
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mDrawable.draw(canvas);
}

}

2013年12月22日

SharedPreferences Code

SharedPreferences

可以使用SharedPreferences保存數據:
boolean,float,int,long,string
這些數據將保持不變,即使應用程序被終止。

記錄
SharedPreferences.Editor editor = spref.edit();
editor.clear();
editor.putInt("KEY_FLAGA", ImageOne.getFlagA());
editor.putInt("KEY_COLOR", PaintOne.getPaintColor());
editor.commit();

讀取
SharedPreferences spref;
spref = getPreferences(MODE_PRIVATE);
int IntFLAGA = spref.getInt("KEY_FLAGA", 0);
//0為預設值

2013年1月24日

TextView Code

TextView Code

class TextViewTitle extends TextView implements OnClickListener {
public TextViewTitle(Context context) {
super(context);
this.setId(9011);
this.setBackgroundColor(Color.argb(255, 255, 255, 255));
this.setText("SPEND");
}

public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}

2013年1月22日

EditText Code


EditText Code

class EditTextAmount extends EditText implements OnClickListener ,OnKeyListener{
public EditTextAmount(Context context) {
super(context);
this.setId(9002);
this.setBackgroundColor(Color.argb(255, 255, 255, 255));
this.setText("99");
}

public void onClick(View arg0) {
// TODO Auto-generated method stub

}

public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
return false;
}
}


//設置密碼為不可見。
this.setTransformationMethod(PasswordTransformationMethod.getInstance());

//字數限制的設置

this.setFilters(new InputFilter[]{newInputFilter.LengthFilter(100)});

//調用數字鍵盤

this.setInputType(InputType.TYPE_CLASS_NUMBER);

//設置輸入類型和鍵盤為英文

this.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);

//監聽事件enter
輸入完成

editTextA.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //actionId == XX_SEND 或者 XX_DONE時都觸發        //或者event.getKeyCode == ENTER  event.getAction == ACTION_DOWN時也觸發        //注意,這是一定要判斷event != null。因為在某些輸入法上會返回null        if (actionId == EditorInfo.IME_ACTION_SEND                || actionId == EditorInfo.IME_ACTION_DONE                || (event != null && KeyEvent.KEYCODE_ENTER == event.getKeyCode() && KeyEvent.ACTION_DOWN == event.getAction())) {
            //處理事件            if (spinnerA != null) {
                init(spinnerA.getSelectedItemPosition());
                myAdapter.notifyDataSetChanged();
            }
        }
        return false;
    }
});

//監聽事件
輸入文字變更
editTextA.addTextChangedListener(new TextWatcher() {
            @Override            public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub                System.out.println("afterTextChanged || 按下後");

            }

            @Override            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
// TODO Auto-generated method stub                System.out.println("beforeTextChanged || 按下前");
            }

            @Override            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
// TODO Auto-generated method stub                System.out.println("onTextChanged || 按下中");
            }
        });

2013年1月13日

Android String to Date And Date to String

String to Date


//欲轉換的日期字串
String dateString = "2013-01-12 23:19:54";
//設定日期格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//進行轉換
Date date = sdf.parse(dateString);
System.out.println(date);


Date to String


Date dt=new Date();
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String time=sdf.format(dt);

取得星期幾


SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date dt =sdf.parse("2012/12/31 11:49:00");
Calendar calendar = Calendar.getInstance();//取得目前時間
calendar.setTime(dt);//或是設定指定時間
int day=calendar.DAY_OF_WEEK;
//1~7代表星期日至星期六

DateFormat 和 SimpleDateFormat



DateFormat是一個格式化和解析日期或時間的抽象類. 它的子類, 如SimpleDateFormat, 允許進行格式化(即date -> text), 分析(text -> date), 規範化. 該日期以Date對象表示, 或自1970年1月1日, 格林尼治標準時間(GMT)00:00:00起以毫秒表示.

SimpleDateFormat是一個用於本土(locale-sensitive)格式化和解析日期方式的具體類.

Example
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy  hh:mm:ss a");  
String now = formatter.format(new Date());

時間格式語法
要指定的時間格式, 使用時間模式字符串. 在這個模式中, 所有的ASCII字母被保留為模式字母, 其中定義如下:


時間格式語法
Symbol Meaning Presentation Example
G era designator (Text) AD
y year (Number) 2013
M month in year (Text & Number) July & 07
d day in month (Number) 13
h hour in am/pm (1˜12) (Number) 12
H hour in day (0˜23) (Number) 0
m minute in hour (Number) 30
s second in minute (Number) 55
S fractional second (Number) 978
E day of week (Text) Tuesday
D day in year (Number) 289
F day of week in month (Number) 2 (2nd Wed in July)
w week in year (Number) 28
W week in month (Number) 2
a am/pm marker (Text) PM
k hour in day (1˜24) (Number) 24
K hour in am/pm (0˜11) (Number) 0
z time zone (Text) Pacific Standard Time
Z time zone (RFC 822) (Number) -0800
v time zone (generic) (Text) Pacific Time
V time zone (location) (Text) United States (Los Angeles)
' escape for text ((Delimiter) 'Date='
'' single quote (Literal) 'o''clock'

Android int 和 String 互相轉換的多種方法


int 和 String 互相轉換的多種方法
 
如何將字串 String 轉換成整數 int

(A) int i = Integer.parseInt("12345");
(B) int i = Integer.valueOf("12345").intValue();

字串String轉成 Double,Float,Long 的方法相同


如何將整數 int 轉換成字串 String
(A) String s = String.valueOf(12345);
(B) String s = Integer.toString(12345);
(C) String s = "" + 12345;

Double,Float,Long 轉成字串String的方法相同

Android Eclipse DDMS -To find database path 資料庫路徑

STEP 1
Eclipse/Window/Open Perspective/Other

STEP 2
選擇 DDMS

STEP 3
DDMS視窗,尋找/data/data/project_name/databases



STEP 4
結果顯示





Android使用SQLite/SQLiteDatabase/SQLiteOpenHelper 建立資料庫


建立一個SQLiteOpenHelper的class類別


import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MySQLiteHelper extends SQLiteOpenHelper  implements DatatableString{

public MySQLiteHelper(Context context) {
super(context, DatatableString.MYDATABASE, null,DatatableString.MYDATABASE_VERSION);
Log.d("MySQLiteHelper","public MySQLiteHelper(Context context)");
}

@Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
Log.d("MySQLiteHelper", "public void onCreate(SQLiteDatabase arg0)");
String DATABASE_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+DatatableString.MYTABLENAME+" ("
+ "F_ID INTEGER PRIMARY KEY,"
+ "F_A CHAR(10),"
+ "F_DATETIME DATE,"
+ "F_ITEM_A VARCHAR(100),"
+ "F_ITEM_B VARCHAR(100),"
+ "F_COST INTEGER,"
+ "F_COMMEND VARCHAR(1000),"
+ "F_PICTURE_PATH CHAR(1000),"
+ "F_BACK_A CHAR(100),"
+ "F_BACK_B CHAR(100)"
+ ");";
// 建立moneyTable資料表
arg0.execSQL(DATABASE_CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub

}
}

interface DatatableString
{
public static final String MYDATABASE="mydatatable.db";// 資料庫名稱
public static final int MYDATABASE_VERSION = 1; // 資料庫版本
public static final String MYTABLENAME="mytableone";
}

2013年1月5日

Android Paint 基本方法


//設置畫筆
Paint paint = new Paint();

 //畫字String
設定顏色
paint.setColor(Color.BLACK)
paintTextA.setARGB(255, 200, 200, 200)

paint.setTextSize(45)//設定字體大小
paint.setAntiAlias(true)//無鋸齒效果

paint.setFakeBoldText(true); //true為粗體,false非粗體
paint.setTextSkewX(-0.5f); //負數表示右斜,正數左斜
paint.setUnderlineText(true); //true為下畫線,false為非下畫線
paint.setStrikeThruText(true); //true為刪除線,false非刪除線

canvas.drawText("Jacky And Justin", 150, 550, paint)

 //設置畫布底色
 _canvas.drawColor(Color.WHITE);

 //設置畫筆顏色
paint.setColor(Color.GRAY);
paint.setColor(Color.BLUE);

 //畫圓
 _canvas.drawCircle(160, 160, 150, paint);

 //畫方

 Rect rect = new Rect(100, 110, 150, 130);
 _canvas.drawRect(rect, paint);

 //畫圓角方
 RectF rectf = new RectF(200, 110, 220, 130);
 _canvas.drawRoundRect(rectf,10,10, paint);

 //畫弧
 RectF oval = new RectF(50, 150, 270, 250);
 _canvas.drawArc(oval, 180, -180, true, paint);

//畫圓環
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(50);
_canvas.drawCircle(250.5f, 430.5f, 100.0f, paint);

如何使用ANDROID模擬器截圖

如何使用ANDROID模擬器截圖

STEP 1
資料夾尋找點擊android sdk/tools/ddms.bat

STEP 2
選取你的模擬器

STEP 3
選取Device/Screen capture

STEP 4
模擬器顯示圖面,你可以Save儲存。
圖面顯示大小為模擬器解析度大小。
圖面格式為png
更新頁面Refresh

2013年1月1日

Android Activity 流程紀錄


Android Activity
簡單的總結幾個動作
onCreate()用來做程式的初使化動作
onDestory()通常都拿來把onCreate()時的資料做釋放的動作
onPause()時把需要保存的資料保存
onResume()把保存的資料拿回來使用

Android Application遵循的動作流程:

一般啟動
onCreate>>onStart>>onResume
啟動一個 Activity 的基本流程是: 分配資源給這個 Activity(onCreate), 然後將 Activity 內容顯示到螢幕上(onStart), 在一切就緒後, 取得螢幕的控制權(onResume), 使用者可以開始使用這個程式.

呼叫另一個 Activity
onPause(1)>>onCreate(2)>>onStart(2)>>onResume(2)>>onStop(1)
先凍結原本的 Activity, 再交出直接存取螢幕能力(onPause )的過程,直到 Activity 2 完成一般啟動流程後, Activity 1 才會被停止.

回復原 Activity
onPause(2)>>onRestart(1)>>onStart(1)>>onResume(1)>>onStop(2)>>onDestroy(2)
按 Back鍵可以回到原本的 Activity.

退出/結束
onPause>>onStop>>onDestroy
如果程式中有直接呼叫 finish 函式來關閉 Activity的話, 系統會暫停(Pause), 停止(Stop)然後銷毀(Destroy).

回收後再啟動
onCreate>>onStart>>onResume
被回收掉的 Activity 一旦又重新被呼叫時, 會像一般啟動一樣再次呼叫 Activity 的 onCreate 函式.

example.appflashlight


package com.example.appflashlight;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RectShape;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MainActivity extends Activity implements IColor {
public int widthPixels = 0;
public int heightPixels = 0;
RelativeLayout layout;
RelativeLayout.LayoutParams params;
// MainView mainView;
ImageButtonA imageButtonA;
ColorDrawView colorDrawView;
SharedPreferences spref;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// setBackgroundColor(Color.argb(255, 50, 50, 50));
spref = getPreferences(MODE_PRIVATE);
int IntFLAGA = spref.getInt("KEY_FLAGA", 0);
Log.e("MainActivity", "IntFLAGA  " + IntFLAGA);
ImageOne.setImageOneflagA(IntFLAGA);

int IntColor = spref.getInt("KEY_COLOR", -14803201);
Log.e("MainActivity", "IntColor  " + IntColor);
PaintOne.setPaintOne(IntColor);

DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
widthPixels = dm.widthPixels;
heightPixels = dm.heightPixels;

layout = new RelativeLayout(this);
layout.setId(20001);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));

params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
MainActivityView mainActivityView = new MainActivityView(this);
mainActivityView.setId(20002);
mainActivityView.setLayoutParams(params);
layout.addView(mainActivityView);

colorDrawView = new ColorDrawView(this);
colorDrawView.setId(859199);
params = new RelativeLayout.LayoutParams(colorDrawView.width,
colorDrawView.height);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(90, 120, 0, 0);
colorDrawView.setLayoutParams(params);
layout.addView(colorDrawView);

Log.e("MainActivity", "MainActivity onCreate");

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
// params.setMargins(20, 20, 20, 20);
// params.addRule(RelativeLayout.ALIGN_RIGHT,layout.getId());
ButtonBmpA buttonBmpA = new ButtonBmpA(this);
buttonBmpA.setLayoutParams(params);
layout.addView(buttonBmpA);

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
// params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.ALIGN_TOP, buttonBmpA.getId());
params.addRule(RelativeLayout.RIGHT_OF, buttonBmpA.getId());
// params.setMargins(20, 20, 20, 20);
ButtonBmpB buttonBmpB = new ButtonBmpB(this);
buttonBmpB.setLayoutParams(params);
layout.addView(buttonBmpB);

params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
params.setMargins(90, 120, 0, 0);
imageButtonA = new ImageButtonA(this);
imageButtonA.setLayoutParams(params);
layout.addView(imageButtonA);

setContentView(layout);
}

public void goSecondActivity() {
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
this.startActivity(intent);
}

public void goThirdActivity() {
Intent intent = new Intent();
intent.setClass(MainActivity.this, ThirdActivity.class);
this.startActivity(intent);
}

@Override
protected void onDestroy() {
super.onDestroy();
// Toast.makeText(this, "OnDestroy()", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "onDestroy()");
}

@Override
protected void onPause() {
super.onPause();
// Toast.makeText(this, "OnPause()", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "onPause()");
}

@Override
protected void onRestart() {
super.onRestart();
Log.e("MainActivity", "onRestart()");
// Toast.makeText(this, "OnRestart() WELCOME BACK", Toast.LENGTH_SHORT)
// .show();
}

@Override
protected void onResume() {
super.onResume();
// Toast.makeText(this, "OnResume()", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "onResume()");
imageButtonA.setBackgroundResource(ImageOne.getflagShow());
colorDrawView.setmPaintColor();
}

@Override
protected void onStart() {
super.onStart();
// Toast.makeText(this, "OnStart()", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "onStart()");
}

@Override
protected void onStop() {
super.onStop();
// Toast.makeText(this, "OnStop()", Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "onStop()");
SharedPreferences.Editor editor = spref.edit();
editor.clear();
editor.putInt("KEY_FLAGA", ImageOne.getFlagA());
editor.putInt("KEY_COLOR", PaintOne.getPaintColor());
editor.commit();

if (CameraOne.getCamera() != null) {
CameraOne.setCamera();
ImageOne.setImageOneflagB();
}
}
}

class MainActivityView extends View {
private ShapeDrawable mDrawable;
private Paint mPaint;
private int width = 0;
private int height = 0;

public MainActivityView(Context context) {
super(context);
// TODO Auto-generated constructor stub
MainActivity mainActivity = (MainActivity) context;
height = mainActivity.heightPixels;
width = mainActivity.widthPixels;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.setBounds(0, 0, width, height);
mPaint = mDrawable.getPaint();
mPaint.setColor(Color.argb(255, 0, 0, 0));
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
mDrawable.draw(canvas);
}
}

class ColorDrawView extends View {
public Bitmap bollBitmap;
private ShapeDrawable mDrawable;
private Paint mPaint;
public int width = 0;
public int height = 0;
private Canvas canvas;

public ColorDrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
MainActivity mainActivity = (MainActivity) context;
bollBitmap = BitmapFactory.decodeResource(mainActivity.getResources(),
R.drawable.image_0);
width = bollBitmap.getWidth();
height = bollBitmap.getHeight();

mDrawable = new ShapeDrawable(new RectShape());
mDrawable.setBounds(0, 0, width, height);

mPaint = mDrawable.getPaint();
mPaint.setColor(PaintOne.getPaintColor());
mPaint.setMaskFilter(new BlurMaskFilter(20, BlurMaskFilter.Blur.INNER));
// mPaint=PaintOne.getPaintOne();
}

public void setmPaintColor() {
mPaint.setColor(PaintOne.getPaintColor());
invalidate(); // 每呼叫一次就會重新繪圖onDraw()
}

@Override
protected void onDraw(Canvas _canvas) {
// TODO Auto-generated method stub
canvas = _canvas;
canvas.drawBitmap(bollBitmap, 0, 0, mPaint);
mDrawable.draw(canvas);
}

}
這是第一天