搜尋此網誌

2015年1月22日 星期四

【Android】String Resource

紀錄一下
ref:http://developer.android.com/guide/topics/resources/string-resource.html#FormattingAndStyling

Formatting and Styling


Here are a few important things you should know about how to properly format and style your string resources.

Escaping apostrophes and quotes

If you have an apostrophe or a quote in your string, you must either escape it or enclose the whole string in the other type of enclosing quotes. For example, here are some stings that do and don't work:
<string name="good_example">"This'll work"</string>
<string name="good_example_2">This\'ll also work</string>
<string name="bad_example">This doesn't work</string>
<string name="bad_example_2">XML encodings don&apos;t work</string>

Formatting strings

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:
<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>
In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

Styling with HTML markup

You can add styling to your strings with HTML markup. For example:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="welcome">Welcome to <b>Android</b>!</string>
</resources>
Supported HTML elements include:
  • <b> for bold text.
  • <i> for italic text.
  • <u> for underline text.
Sometimes you may want to create a styled text resource that is also used as a format string. Normally, this won't work because the String.format(String, Object...) method will strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered withfromHtml(String), after the formatting takes place. For example:
  1. Store your styled text resource as an HTML-escaped string:
    <resources>
      <string name="welcome_messages">Hello, %1$s! You have &lt;b>%2$d new messages&lt;/b>.</string>
    </resources>
    In this formatted string, a <b> element is added. Notice that the opening bracket is HTML-escaped, using the&lt; notation.
  2. Then format the string as usual, but also call fromHtml(String) to convert the HTML text into styled text:
    Resources res = getResources();
    String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);
    CharSequence styledText = Html.fromHtml(text);
Because the fromHtml(String) method will format all HTML entities, be sure to escape any possible HTML characters in the strings you use with the formatted text, using htmlEncode(String). For instance, if you'll be passing a string argument to String.format() that may contain characters such as "<" or "&", then they must be escaped before formatting, so that when the formatted string is passed through fromHtml(String), the characters come out the way they were originally written. For example:
String escapedUsername = TextUtil.htmlEncode(username);
Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), escapedUsername, mailCount);
CharSequence styledText = Html.fromHtml(text);

2015年1月15日 星期四

【Android】java.lang.ClassCastException: android.widget.... cannot be cast to android.widget....

Solve method:

Eclipse tends to mess up your resources every now and then. This leads to some odd behavior such as strings and images being swapped all over your app, and more commonly classCastException(s), which happen when Eclipse switches your Views' ids around.
A few solutions to that problem:
Clean your project.
Modify an xml layout file and save.
Delete your R file. (Don't worry it will be automatically generated again).
Basically anything that makes your project rebuild and re-generate the R file.

ref:

2015年1月13日 星期二

【Android】onActivityResult()和onResume()誰先執行

ref:onActivityResult()和onResume()的調用順序問題

protected void onActivityResult (int  requestCode, int resultCode, Intent  data)
Since: API Level 1 Called when an  activity you launched exits, giving  you the requestCode you started it  with, the resultCode it returned, and  any additional data from it. The resultCode will be RESULT_CANCELED if  the activity explicitly returned that,  didn't return any result, or crashed  during its operation. You will receive this call immediately before onResume() when your activity is  re-starting.

由此可見onActivityResult()發生在onResume()之前

【Java】全域常數???

ref:
What is the better way of publishing global constants in Java?

Method 1: final class with public static final fields
public final class CNST{
    private CNST(){}
    public static final String C1;
    public static final String C2;
    static{
       C1="STRING1";
       C2="STRING2";
    }
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.C1);
//System.out.println(CNST.C2);
Method 2: singleton with enum
public enum CNST{
    INST;
    public final String C1;
    public final String C2;
    CNST{
       C1="STRING1";
       C2="STRING2";
    }
}
//so I could call C1, C2 like:
//...some code...
//System.out.println(CNST.INST.C1);
//System.out.println(CNST.INST.C2);
Method1的方法較好。

【Android】Intent & Bundle傳遞資料(含傳自定義物件及全域變數)

ref:http://goo.gl/nrAX9g

[方法一]從A.class傳到B.class

比喻: 某人要從 A地到B地  靠的是交通工具(Intent )

A.class 目前的Class
B.class 目的Class

Intent i = new Intent();
i.setClass(A.this,B.class)
startActivity(i);
or
Intent i = new Intent(A.this,B.class);
startActivity(i);//開始跳往要去的Activity

如果要結束A.class 要加上這行

A.this.finish();//結束目前Activity

[方法二]傳遞資料從A傳到B
比喻: 某人要從 A地帶東西(Bundle)到B地  靠的是交通工具(Intent), 所以他把東西(Bundle) 放在交通工具上(Intent)一起帶去
1.Intent

A.class(傳送資料)
//new一個intent物件,並指定Activity切換的class
Intent intent = new Intent();
intent.setClass(A.this,B.class);
intent .putExtra("name",name);//可放所有基本類別
//切換Activity
startActivity(intent);

B.class(接收資料)
Intent intent = this.getIntent();
//取得傳遞過來的資料  
String name = intent.getStringExtra("name"); 

2.Bundle+Intent

用法簡介:

A.class(傳送資料)
//new一個intent物件,並指定Activity切換的class
Intent intent = new Intent();
intent.setClass(A.this,B.class);
//new一個Bundle物件,並將要傳遞的資料傳入
Bundle bundle = new Bundle();
bundle.putDouble("age",age );//傳遞Double
bundle.putString("name",name);//傳遞String
//將Bundle物件傳給intent
intent.putExtras(bundle);
//切換Activity
startActivity(intent);

B.class(接收資料)
Bundle bundle = getIntent().getExtras(); 
String name = bundle.getString("name");
double age = bundle.getDouble("age");
[方法三]傳遞資料從A傳到B後,再由B傳參數回去A
比喻: 甲拜託乙 從A地到B地買東西回來 ,靠的是交通工具(Intent),

乙回來的話東西送到甲的地址(requestCode/resultCode)

A.class
Intent intent = new Intent(A.this,B.class);
//requestCode(識別碼) 型別為 int ,從B傳回來的物件將會有一樣的requestCode
startActivityForResult(intent,requestCode);
?
B.class

Intent intent = getIntent();
Bundle bundle = new Bundle();
bundle.putString("name",name); 
intent.putExtras(bundle);
setResult(requestCode, intent); //requestCode需跟A.class的一樣
B.this.finish();

然後要在A.class裡複寫onActivityResult 才能接收B傳回的值
Intent intent = getIntent();
@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        
        switch(resultCode){//resultCode是剛剛妳A切換到B時設的resultCode 
        case requestCode://當B傳回來的Intent的requestCode 等於當初A傳出去的話
            String result = data.getExtras().getString("name");
             
            break;
        
        }
      
    }
[方法四]傳遞自定義物件
1.利用Serializable or Parcelable

Bundle.putSerializable(Key,Object);
Bundle.putParcelable(Key, Object);
這兩種都必須時做接口
今天講Serializable
要利用 Serializable 傳遞物件的話 
妳的物件必須  implements Serializable
public class CustomObject implements Serializable {
private static final long serialVersionUID = -7060210544600464481L;
//省略以下 為你class的內容
}
然後在要傳資料的B.class裡

CustomObject co_b = new CustomObject ();

Intent i=new Intent();
Bundle bundle=new Bundle();
bundle.putSerializable("CustomObject ", co_b); 
i.putExtras(bundle);
startActivity(i);

2.利用全域變數 簡單使用別的class的自定義物件
在A.class裡
public class A extends Activity{
   public static CustomObject co_a = null; //一定要加static 且 public
   //以下intent從A到B的內容省略
}
在B.class裡
CustomObject co_b = A.co_a;//直接使用A的static物件