2012年3月27日 星期二

Image Transition

從一張圖,經過5秒轉換成另一張圖

res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center"
        android:src="@drawable/yih950909_01_300" />

</LinearLayout>

**************
res/drawable/kids_photos.xml:


<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/yih950909_01_300"/>
<item android:drawable="@drawable/usa_03y_01_300"/>
</transition>

****************************

main.java:


public class Cq_ImgTransitionActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
//設定轉換圖像來自 res/drawable/kids_photos.xml
        Resources res = getResources();
        TransitionDrawable tranisiton = (TransitionDrawable)res.getDrawable(R.drawable.kids_photos);
        ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
        mImageView.setImageDrawable(tranisiton);
     
      //開始轉換到第2張圖像
        tranisiton.startTransition(5000);
    }
}


ImageView

ImageView Programmatically


public class Cq_Img01Activity extends Activity {
    /** Called when the activity is first created. */

LinearLayout mLinearLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     
        //Create a LinearLayout for ImageView
        mLinearLayout = new LinearLayout(this);
     
        //Create ImageView obj
        ImageView imageview = new ImageView(this);
        imageview.setImageResource(R.drawable.imgexample);
     
        //Set size
        imageview.setAdjustViewBounds(true);
        imageview.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
     
        mLinearLayout.addView(imageview);
        setContentView(mLinearLayout);
    }
}

2012年3月22日 星期四

Location GPS



在 Manifest.xml 加上:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>

Main.java:

//如果沒有加上 implements LocationListener;就得實作 mLocationListener 介面

public class Cq_LocationGPSActivity extends Activity implements LocationListener{
    /** Called when the activity is first created. */
private LocationManager mLocationManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mLocationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
        TextView tv08 = (TextView)findViewById(R.id.textView8);
        tv08.setText("LOCATION-GPS");
    }
    
    

@Override
protected void onResume() {
// TODO Auto-generated method stub
if (mLocationManager != null){
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
super.onResume();
}



@Override
protected void onPause() {
// TODO Auto-generated method stub
if (mLocationManager != null){
mLocationManager.removeUpdates(this);
}
super.onPause();
}



@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
TextView tv1 = (TextView)findViewById(R.id.textView1);
TextView tv2 = (TextView)findViewById(R.id.textView2);
TextView tv3 = (TextView)findViewById(R.id.textView3);
TextView tv4 = (TextView)findViewById(R.id.textView4);
TextView tv5 = (TextView)findViewById(R.id.textView5);
TextView tv6 = (TextView)findViewById(R.id.textView6);
TextView tv7 = (TextView)findViewById(R.id.textView7);
tv1.setText("Latitude :  " + String.valueOf(location.getLatitude()));
tv2.setText("Longitude : " + String.valueOf(location.getLongitude()));
tv3.setText("Accuracy :" + String.valueOf(location.getAccuracy()));
tv4.setText("Latitude : " + String.valueOf(location.getAltitude()));
tv5.setText("Time : " + String.valueOf(location.getTime()));
tv6.setText("Speed : " + String.valueOf(location.getSpeed()));
tv7.setText("Bearing : " + String.valueOf(location.getBearing()));
}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
switch (status){
case LocationProvider.AVAILABLE:
Log.v("Status", "AVALIABLE");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.v("Status", "OUT_OF_SERVICE");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.v("Status", "TEMPORARILY_UNAVAILABLE");
break;
}
}
}

**********************************
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >


    <TextView
        android:id="@+id/textView8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    

</LinearLayout>



2012年3月19日 星期一

Widget_1

要做個常駐程式的步驟:

1. 在 Manifest.xml 宣告常駐程式。
2. 實做常駐程式資訊檔案:res/xml/appwidget_info.xml
3. 實做一個layout檔來顯示: res/layout/layout_sample.xml
4. 實做一個AppWidgetProvider (也就是main.java),在此例裡App_WidgetActivityProvider.java

*標示圖:74的倍數-2, e.g. 72, (74*4)-2 = 294

****************************************


public class App_WidgetActivityProvider extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onUpdate(context, appWidgetManager, appWidgetIds);
}


****************************************
App_Widget.manifest:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cq.lin.app.widget"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <application
        android:icon="@drawable/widget"
        android:label="@string/app_name" >
        <receiver android:name="App_Widget"
            android:label="CQ's Simple Widget"
            android:icon="@drawable/widget">
            
            <intent-filter >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/appwidget_info"/>
        </receiver>

</application>

</manifest>



****************************************
res/xml/appwidget_info.xml:



<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:minWidth="72dp"
    android:minHeight="72dp"
    android:updatePeriodMillis="86400000"
    android:initialLayout="@layout/layout_sample" >

</appwidget-provider>

***************************************
res/layout/layout_sample.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/appwidget_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#ff000000"
        android:background="#ffffff"
        android:text="Hello, Life is tough! (by Widget)" />

</LinearLayout>

2012年3月18日 星期日

Context IO 私有資料夾的檔案寫入和讀取


私有資料夾(Context) 的檔案寫入和讀取:  /data/data/com.example.package.io




利用下述的方法:

    openFileInput (String fileName); 讀出資料
    openFileOutput (String name, int mode); 寫入資料
    fileList ();
    deleteFile(String fileName);



main.java:



public class IO01Activity extends Activity {
    /** Called when the activity is first created. */

public static final String ENCORDING = "UTF-8";
String fileName = "test01.txt"; //設定檔案
String message = "一開始寫入的資料";
TextView tv;
EditText et;
Button inputBtn;
Button deleteInputBtn;
Button editBtn;
Button deleteFileBtn;
InputMethodManager inputMgr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
     
     
        tv = (TextView)findViewById(R.id.textView01);
        et = (EditText)findViewById(R.id.editText1);
        inputBtn = (Button)findViewById(R.id.button1);
        deleteInputBtn = (Button)findViewById(R.id.button3);
        editBtn = (Button)findViewById(R.id.button4);
        deleteFileBtn = (Button)findViewById(R.id.button2);
     
//        inputMgr = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//        inputMgr.toggleSoftInput(0, 0);
     
     
        //重新輸入內容
        deleteInputBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
et.setText("");

}
});
     
     
        //完成,顯示檔案內容
        inputBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String message = et.getText().toString(); //拿到使用者輸入的字串
writeFileData (fileName, message); //寫進去檔案test01.txt

//完成時將keyboard 隱藏,以不至於檔到螢幕的View
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(et.getWindowToken(), 0);

//將結果顯示在螢幕上
String result = readFileData (fileName); //去test01.txt取出內容,顯示在螢幕上
tv.setText(result);

et.setText("");// 清空 editText box
}
});
     
     
        //修改檔案內容
        editBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteFile(fileName);
et.setText(tv.getText().toString());

}
});
     
     
     
     
        //刪除檔案的全部內容
        deleteFileBtn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
deleteFile(fileName);


tv.setText("新檔案:");

}
});
    }
 
 
  //方法:向指定檔案中寫入指定的資料
    public void writeFileData (String fileName, String message){
    try {
    FileOutputStream fos = openFileOutput(fileName, MODE_APPEND);
    byte[] bytes = message.getBytes();//將要寫入的字串轉換為byte陣列
    fos.write(bytes);                             //將byte陣列寫入檔案
    fos.close();                                      //關閉FileOutputStream物件
   
    } catch (Exception e) {
    e.printStackTrace();                     //捕獲異常並列印
    }
    }// end of writeFileData
 
 
  //方法:打開指定檔,讀取其資料,返回字串物件
    public String readFileData (String fileName){
    String result = "";
    try {
    FileInputStream fis = openFileInput(fileName);
    int length = fis.available();                                                //獲取檔案長度
    byte[] buffer = new byte [length];                                    //新建byte陣列用於讀入資料
    fis.read(buffer);                                                                //將檔案內容讀入到byte陣列中
    result = EncodingUtils.getString(buffer, ENCORDING);//將byte陣列轉換成指定格式的字串
    fis.close();                                                                         //關閉檔案輸入串流
    } catch (Exception e) {
    e.printStackTrace();                                                          //捕獲異常並列印
    }
    return result;                                                                      //返回讀到的資料字串
    }
 
 
}

*********************************************
res/layout/main.xml:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </EditText>

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="重新輸入input格的內容" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="完成,顯示檔案內容" />
 
     <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="修改檔案內容" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="刪除此檔案的全部內容" />

    <TextView
        android:id="@+id/textView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="新檔案:" />

</LinearLayout>


**********************************************
也可以將資料檔存在 res/raw/test1.txt  or assets/test2.txt 如下:
但只可以讀出。

利用:



public class IORawAssetsActivity extends Activity {
    /** Called when the activity is first created. */

public static final String ENCODING = "UTF-8";
TextView tv1, tv2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
        tv1 = (TextView) findViewById(R.id.textView1);
        tv2 = (TextView) findViewById(R.id.textView2);
        tv1.setText(getFromRaw("test1.txt"));
        tv2.setText(getFromAssets("test2.txt"));
    }
 
  //方法:從resource中的raw資料夾中獲取檔案並讀取資料
    public String getFromRaw (String fileName) {
    String result = "";
    try {
    InputStream is = getResources().openRawResource(R.raw.test1);//從raw中取檔案
    int length = is.available();//獲取檔案的位元組數
    byte [] buffer = new byte [length];//新建byte陣列
    is.read(buffer);//將檔案中的資料讀取到byte陣列中
    result = EncodingUtils.getString(buffer, ENCODING);//將byte陣列轉換成指定格式的字串
    is.close();//關閉
    }catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }// end of getFromRaw()
 


or from assets:
 
    public String getFromAssets(String fileName) {
    String result = "";
    try {
    InputStream is = getResources().getAssets().open(fileName);
    int length = is.available();
    byte [] buffer = new byte [length];
    is.read(buffer);
    result = EncodingUtils.getString(buffer, ENCODING);
    }catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }
 
}

參考:
http://blog.csdn.net/dww410/article/details/5399094

android -- image (Matrix)


******************************************
縮小圖:

   @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        view = (ImageView) findViewById(R.id.imageView1);
       
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.butterfly);
        bmpWidth = bitmap.getWidth();
        bmpHeight = bitmap.getHeight();
        scaleOriginal = 1;
        loadImg();

}



private void loadImg(){
     Matrix matrix = new Matrix();
     scaleOriginal *= 0.5;
     matrix.postScale(scaleOriginal, scaleOriginal);
     Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);
     view.setImageBitmap(resizedBitmap);
    }


**********************************************************************

 DisplayMetrics dm = new DisplayMetrics();
     
        //取得手機解析度
        getWindowManager().getDefaultDisplay().getMetrics(dm);
     
        //設定顯示寬高
        dispalyWidth = dm.widthPixels;
        displayHeight = dm.heightPixels - 80;
     
     
        //linearLayout = (LinearLayout)findViewById(R.id.linearLayout01);
*******************************************************************


DisplayMetrics displayMetrics = new DisplayMetrics();
((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(displayMetrics);
int statusBarHeight;
switch (displayMetrics.densityDpi) {
    case DisplayMetrics.DENSITY_HIGH:
        statusBarHeight = HIGH_DPI_STATUS_BAR_HEIGHT;
        break;
    case DisplayMetrics.DENSITY_MEDIUM:
        statusBarHeight = MEDIUM_DPI_STATUS_BAR_HEIGHT;
        break;
    case DisplayMetrics.DENSITY_LOW:
        statusBarHeight = LOW_DPI_STATUS_BAR_HEIGHT;
        break;
    default:
        statusBarHeight = MEDIUM_DPI_STATUS_BAR_HEIGHT;
}

*************************************************




//縮放圖片
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);

//重新縮放 Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bmpWidth, bmpHeight, matrix, true);