搜尋此網誌

2014年10月27日 星期一

【Android】Fragment Tabs example

【Android】解決 Unable to execute dex: Multiple dex files define


[方法一]
I had the same problem, quite weird because it was happening only when using Eclipse (but it was OK with Ant). This is how I fixed it:
  • Right click on the Project Name
  • Select Build Path -> Configure Build Path
  • In Java Build Path, go to the tab Order and Export
  • Uncheck your .jar library
Only sometimes: In Order and Export tab I did not have any jar library there, so I have unchecked Android Private Libraries item. Now my project is running.

[方法二]
NON OF THE ABOVE METHODE WORKED FOR ME BUT MINE IS WORKED LIKE A CHARM!
The problem happens when user builds the dependent library with eclipse. So to get the solution
Step 1: Delete the library (like support library project v4 or v13) from Eclipse with delete workspace source permanantly
Step 2: Re import the library and include it to your project
Step 3: Clean and Rebuild
DONE!
 
ref:
http://stackoverflow.com/questions/7870265/unable-to-execute-dex-multiple-dex-files-define-lcom-myapp-rarray?page=1&tab=votes#tab-top 



【Android】android:typeface

Android字型改變,利用TextView內的setTypeface來指定使用字型,但必須透過外部資源assets,引用外部的字體(True Type Font),藉由Typeface類別的createFromAsset方法,讓TextView透過setTypeface來改變字型。

  1. Step1.在/res中,建立fonts資料夾
  2. 將外部字型檔放在fonts資料夾內(字型檔必須是 .ttf )

ref:
Victoria IT Journal

2014年10月25日 星期六

【Android】array to json/json to array

private void JSONEncode() throws JSONException {
        JSONArray jsonArray = new JSONArray();
 
        for (int i = 0; i < name.length; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", name[i]);
            jsonObject.put("id", id[i]);
            jsonObject.put("score", score[i]);
            jsonArray.put(jsonObject);
        }
 
        Log.i("JSON String", jsonArray.toString());
        JSONString = jsonArray.toString();
    }
 
    private void JSONDecode() throws JSONException {
        JSONArray jsonArray = new JSONArray(JSONString);
        Log.i("Number of Entries", Integer.toString(jsonArray.length()));
 
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            int id = jsonObject.getInt("id");
            double score = jsonObject.getDouble("score");
            Log.i("Entry", "name: " + name + ", id: " + id + ", score: " + score);
        }
    }
ref:Alan's Development Notes

【Android】Dashboards




ref:
http://goo.gl/RV80O4

2014年10月24日 星期五

【Android】自訂Activity頁面切換效果 overridePendingTransition

類似PowerPoint在切換頁面的效果

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); 

 需添加在finsh()或startactivity()之後

 ex.

Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_up, R.anim.slide_out_down);  

 所以需要在res/anim添加對應的xml檔
相關範例可以在 sdk\platforms\android-21\data\res\anim中就可以找到

android2.0也就是level 5之後都有範例可以參考


(實現淡入淡出的效果)android.R.anim.fade_in, android.R.anim.fade_out;
(由左向右滑入的效果)android.R.anim.slide_in_left, android.R.anim.slide_out_right

 (由上向下滑入的效果)android.R.anim.slide_in_up, android.R.anim.slide_out_down

當然也可以自定義動畫效果

2014年10月23日 星期四

【Android】Android library projects cannot be launched 解決辦法


如圖顯示, "Android library projects cannot be launched"。
解決辦法:
在專案按右鍵>Properties>Android>Library區塊中>Is Library勾選取消即可。

ref:

【Android】R cannot be resolved to a variable原因和解決辦法

如果一開始預設選的sdk是4.x以上res/底下會多了各一個value-v11, value-v14 資料夾,用來放一些layout/theme。

這些layout是根據不同的SDK version去gen出來的

其實它的目的就是要你吃它新推出的action bar的概念!

但是如果你把project default sdk version改成2.x,2.X SDK不認得那兩個資料夾是什麼!!!

所以R.java會一直build不出來!

解決辦法就是把那兩個資料夾(value-v11, value-v14 資料夾)砍了!


備註:
  • layout裡面以前有一個attribute是"fill_parent",但在某個版本SDK被deprecated!改成"match_parent"
  • 而4.X就是用match_parent, 如果使用2.x sdk就要"把match_parent改成fill_parent"

ref:
Ken Yang 筆記



【Android】使用 ViewHolder Pattern改善Adapter效率

To improve performance, we should modify the custom adapter by applying the ViewHolder pattern which speeds up the population of the ListView considerably by caching view lookups for smoother, faster item loading:

public class UsersAdapter extends ArrayAdapter<User> {
// View lookup cache
private static class ViewHolder {
TextView name;
TextView home;
}
 
public UsersAdapter(Context context, ArrayList<User> users) {
super(context, R.layout.item_user, users);
}
 
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
User user = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_user, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.tvName);
viewHolder.home = (TextView) convertView.findViewById(R.id.tvHome);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.name.setText(user.name);
viewHolder.home.setText(user.hometown);
// Return the completed view to render on screen
return convertView;
}
}

2014年10月21日 星期二

【Android】Handler example

ref:
http://examples.javacodegeeks.com/android/core/os/handler/android-handler-example/

http://andcooker.blogspot.tw/2012/09/android-runnable-handler.html

http://iamshiao.blogspot.tw/2010/12/androidhandlerthread.html

http://imax-live.blogspot.tw/2012/12/progressbar_18.html

http://bluequiet.blogspot.tw/2014/09/service-handler-thread.html 

http://iamshiao.blogspot.tw/2010/12/androidhandlerthread.html

 http://blog.csdn.net/veryitman/article/details/6611138

【Android】網路上找的 還沒看過

希望連結不要斷掉

http://fecbob.pixnet.net/blog/category/1806971

http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html

http://imax-live.blogspot.tw/2014/10/ym-android-source-code.html

【Android】 背景作業處理


Android的背景作業主要有三種
  1. Thread
    • HandlerThread
  2. AsyncTask
  3. Handler
後兩者可以做的事情差不多,Handler使用上比較簡單,但code的可讀性比較差,AsyncTask需另外subclass一個新的類別,但可讀性比較好。
Android的操作,只要超過5秒沒回應(或OnCreate()超過10秒),程式就會被當作無回應,而系統會丟出ANR(Application No Response Exception)。所以,比較耗時費工的動作,都應該考慮用背景作業的方式來完成。常見耗時的工作有。
  1. 網路相關的動作
  2. 資料庫的動作
  3. 檔案操作
  4. 複雜的計算
在設計時,應該考慮較糟的情況,而不是開發者當時的環境




ref:
http://blog.kent-chiu.com/blog/2012/03/19/background_processing/

2014年10月20日 星期一

【Android】錯誤: Invalid file name: must contain only [a-z0-9_.]

錯誤: Invalid file name: must contain only [a-z0-9_.] 

解決辦法:
  • layout文件的檔名是不能有大寫字母的。

【Android】Android ImageButton with a selected state?


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_selected="true"
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>


And then in java:
//assign the image in code (or you can do this in your layout xml)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

}); 
from http://stackoverflow.com/questions/2604599/android-imagebutton-with-a-selected-state

【Android】設定螢幕方向

為了避免程式執行途中,使用者突然改變手機手持方向,造成Android裝置activity重新onCreate,導致一些錯誤發生,在想到解決辦法之前。先固定Android裝置螢幕方向。

要設定手機程式螢幕的方向,必須在Manifest.xml的activity裡面設定android:screenOrientation
至於方向類型有幾種:
  • landscape – 橫向
  • portrait – 縱向
  • user – 使用者當前所選方向
  • behind – 下一個要顯示的Activity的Orientation值
  • sensor – 根據方向感測器確定方向,當使用者轉動手機時方向會跟著改變
  • nosensor – 忽略sensor,轉動手機畫面不會跟著變動

如下例所示:

<activity android:name=".test"
          android:label="@string/app_name"
          android:screenOrientation="portrait">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

【Android】Custom ExpandableListView 例子

覺得還可以讀得下去

http://www.mysamplecode.com/2012/10/android-expandablelistview-example.html
http://www.allenj.net/archives/3644
http://weaker.mine.nu/wp/2013/03/basic-expandablelistview/
http://iainstnote.blogspot.tw/2012/07/tqc-android-drop-down-menu108.html
http://androidexample.com/Custom_Expandable_ListView_Tutorial_-_Android_Example/index.php?view=article_discription&aid=107&aaid=129
http://custom-android-dn.blogspot.tw/2013/01/how-to-create-custom-expandablelistview.html

【Eclipse】Color Themes

The Eclipse Color Theme Plugin

2014年10月19日 星期日

【Android】layout整理


  • android:layout_width 控制項寬度
  • android:layout_height 控制項高度
    •  "fill_parent" 填滿父控制項(通常是指撐滿螢幕<寬度or高度>)
    •   "wrap_content" 依照內容決定<高度or寬度>
  • ViewGroup
    • LinearLayout
    • AbsoluteLayout
    • RelativeLayout
    • FrameLayout 
  • LinerLayout 屬性
    • android:orientation="vertical" 排列方式由上往下
    • android:orientation="horizontal" 排列方式由左往右
  • RelativeLayout  屬性
    • android:layout_alignParentLeft="10px"  靠左對齊,(吸附邊框左邊)
    • android:layout_alignParentTop   靠上對齊,(吸附邊框上方)
    • android:layout_alignParentRight   靠右對齊,(吸附邊框右邊)
    • android:layout_alignParentBottom  靠下對齊,(吸附邊框下方)
    • android:layout_centerInParent    置中,(計算放在正中間)
    • android:layout_toLeftOf="@id/aaa"       放在aaa的左邊
    • android:layout_toRightOf="@id/bbb"      放在bbb的右邊
    • android:layout_below="@id/ccc"          放在ccc的下面
    • android:layout_above="@id/ddd"          放在ddd的上面 
  • FrameLayout
    FrameLayout可以想成是RelativeLayout的功能閹割版
    RelativeLayout的部份
    1. 能對齊View的框邊
    例如:
    android:layout_alignParentLeft  靠左對齊,(吸附邊框左邊)
    或是
    2. 設定二格View之間的排列關係
    例如:
    android:layout_toLeftOf="@id/aaa"       放在aaa的左邊


  • 而FrameLayout只剩下對齊View的框邊的功能
    用android:layout_gravity來指定
    如果在其中的View有二個設定成一樣的話呢,就會「依序」重疊上去。

    注意一點,只有RelativeLayout和FrameLayout
    才會發生控制項有重疊的現象
    如果版面看似調不出來,可以檢查一下是否為二個控制項重疊,或是版面出界了




    參考網址:
    http://developer.android.com/guide/topics/resources/layout-resource.html 
    http://developer.android.com/guide/topics/ui/declaring-layout.html
    從新建專案看版面layout設計

2014年10月18日 星期六

【Android】Textview刪除線實作

在TextView上加入刪除線

方法如下
TextView textview = (TextView) findViewById(R.id.textview1);
Paint paint = textview.getPaint();
paint.setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
paint.setAntiAlias(true);


轉回來
TextView textview = (TextView) findViewById(R.id.textview1);
Paint paint = textview.getPaint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setAntiAlias(true);

參考網址:
http://jiun-blog.blogspot.tw/2012/06/android-textview-line-through.html

2014年10月17日 星期五

【Android】實作BaseAdapter

最常用的有幾種Adapter:
  • ArrayAdapter:將一組數組連繫到ListView
  • SimpleAdapter:適用於自訂ListView外觀的應用場合
  • BaseAdapter:抽象類別,所以有多個方法需要實作。適用於需要自訂ListView外觀等靈活應用的場合。
  • SimpleCursorAdapter:將一組現有的資料庫或聯絡人等ContentProvider的資料查詢的結果連繫到ListView中

顯示自訂的清單內容
ListView之一:Adapter介紹與使用
【Android】使用BaseAdapter自訂ListView
Android BaseAdapter提升效能的建議實作方式
Android適配器之ArrayAdapter、SimpleAdapter和BaseAdapter的簡單用法與有用代碼片段
ListView 與 BaseAdapter 的實作
Android - ListView + BaseAdapter 的應用
[Android]使用 BaseAdapter客製化 ListView
Android – Asynchronous image loading in ListView

2014年10月16日 星期四

【Android】EditText和Button放在同一行

<?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/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:text="Linear Layout with EditText and Button"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <EditText
            android:id="@+id/editText1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="you can type here ..." />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />
    </LinearLayout>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="15dp"
        android:text="Relative Layout with EditText and Button"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:text="Button" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/button2"
            android:hint="you can type here ..." >
        </EditText>
    </RelativeLayout>

</LinearLayout>
轉載自 http://www.mysamplecode.com/2012/03/android-edittext-button-same-line.html

2014年10月15日 星期三

2014年10月11日 星期六

2014年10月10日 星期五

【Android】Intent.FLAG_ACTIVITY_CLEAR_TOP意思

http://developer.android.com/reference/android/content/Intent.html
If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

照字面翻譯,將目前指定activity開啟,如果除指定外其他的activity是開啟的,則會被關閉。若指定的activity是已經開啟的,則不會重新開啟。

參考:
http://iskens.blogspot.tw/2011/01/android-activity.html

【Android】PendingIntent介紹和用法


  • Intent 是及時啟動的,intent隨activity消失而消失;PendingIntent可以看作是對intent的包裝。
  •  Intent 一般是用來作Activity、 Service、BroadcastReceiver之間傳遞數據,而Pendingintent,一般用在Notification上,可以理解為延遲執行的intent。


  • 簡單來說,Intent指定好要幹嘛後,就去做了。而PedingIntent則是先把某個Intent包好,丟給某個程式,以後再去執行Intent要幹嘛。比如用startActivity(intent)就會直接去啟動和intent關聯的某個程式了。相對的,假設APK1想告訴APK2在某個情況 下,去執行APK3的話,就可以在APK1設定好PendingIntent(內容就是去執行APK3),然後丟過去給APK2,然後APK2在某種情況 下,就去執行PendingIntent,那就會等於執行APK3。這裡不單單是指startActivity,也可以是對Broadcast和 Service進行處理。

  • 那為何不直接在APK2就用startActivity(Intent)寫好要執行 APK3,不就不用丟PendingIntent了?因為APK2要「動態」決定開啟,不同情況下要執行那一支APK,所以不能先寫死。假設使用 startActivity的情況下,如果有A1、B1、C1三支程式都要APK2去執行不同程式,分別為A3,B3和C3,那不就變成APK2的程式要 寫上startActivity(A3)、startActivity(B3)、startActivity(C3)。假設未來還會有新的D3、E3…會 被執行的話,APK2的程式碼,不就無法要不停的調整了。所以利用PendingIntent就可以解決這個問題。
以上節錄自:
http://developer.android.com/reference/android/app/PendingIntent.html
http://sunzone.iteye.com/blog/1998091
http://androidgill.blogspot.tw/2011/12/pendingintent1.html

2014年10月9日 星期四

【Android】Fragments簡介

適用於Android 3.0 (API level 11) and higher


http://jacky-google-android.blogspot.tw/2011/04/android-fragments.html
http://soldierzx0705.blogspot.tw/2013/07/preferencefragment.html

【Android】Class_Name.this的使用

在閱讀Android API Guide

時常看到Class_Name.this的使用

這個用法多用於在nested class中

當inner class必須使用到outer class的this instance時

舉例來說


class Outer{
    String data = "外部類別";

    public class Inner{
        String data = "內部類別";
        public String getOuterData(){
            return Outer.this.data;
        }
    }
}