2012年3月26日 星期一

SimpleAdapter in Android

參考:http://developer.android.com/reference/android/widget/SimpleAdapter.html

首先先看SimpleAdapter 的Constructor


public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

Since: API Level 1
Constructor
Parameters
contextThe context where the View associated with this SimpleAdapter is running
dataA List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row, and should include all the entries specified in "from"
resourceResource identifier of a view layout that defines the views for this list item. The layout file should include at least those named views defined in "to"
fromA list of column names that will be added to the Map associated with each item.
toThe views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter.
可以看到SimpleAdapter 需要五個參數
context   上下文
data       看名字就可以想到是數據源 必須是List of Maps
resource 每個Item的template
from       data要用到的值
to           那些值對應到的id





一個一個解決他們
1.上下文不用說了
2.創建List of Maps

Map<String, String> _Data = new HashMap<String, String>();
_Data.put("Title", "Hello");
_Data.put("Name", "Maca");

Map<String, String> _Data2 = new HashMap<String, String>();
_Data2.put("Title", "你好");
_Data2.put("Name", "馬卡");

List<Map<String, String>> _DataList = new ArrayList<Map<String,String>>() ;

_DataList.add(_Data);
_DataList.add(_Data2);

3.建立layout 看要拖拉點放 還是用打的 以下是範例

<?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/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

4.from:  宣告一個String[]
String[] _StringArray = new String[]{"Title","Name"};
5.from:  宣告一個int[]

int[] _IdArray = new int[]{R.id.tvTitle,R.id.tvName};
6.最後宣告SimpleAdapter

SimpleAdapter _Adapter = new SimpleAdapter(this, _DataList, R.layout.list_template, _StringArray, _IdArray);


7.別忘了把ListView綁定Adapter

ListView _ListView = (ListView)findViewById(R.id.lvMainPage);
_ListView.setAdapter(_Adapter);


效果

2012年3月25日 星期日

MessageBox in Windows Phone 7

MessageBoxResult _Result = MessageBox.Show ("", "Title", MessageBoxButton.OKCancel);

效果如下圖


根據結果 可進一步操作,


if (_Result == MessageBoxResult.OK)
{
}

2012年3月22日 星期四

Convert Big5 To Unicode for windows phone 7

參考:http://forums.create.msdn.com/forums/p/73736/553266.aspx

研究一下發現wp7的library中只提供了Unicode和Utf-8兩種編碼方式,
所以如果要使用網路上big5編碼的文字就要自己轉換了 不然會變亂碼

參考了MicroStrategy的文章之後
自己再重新包裝了一個工具類
需要先下載 這個編碼轉換的文字檔  導入專案中


之後把網路上抓回的Stream(big5)傳進去
就可以輸出想要的Sting(unicode)了~



public class Big5Util
{

    private static Dictionary<int, int> mBIG5_Unicode_MAP = new Dictionary<int, int> ();

    static Big5Util ()
    {
        StreamResourceInfo _ResourceInfo = Application.GetResourceStream (new Uri ("MyDemos;component/Resource/BIG5.TXT", UriKind.RelativeOrAbsolute));

        StreamReader _Reader = new StreamReader (_ResourceInfo.Stream);


        String line;

        while ((line = _Reader.ReadLine ()) != null)
        {
            if (line.StartsWith ("#"))
                continue; // Comments
            string[] lTokens = line.Split (new char[] { '\t' });
            if (lTokens.Length < 2)
                continue; // Not enough tokens
            try
            {
                mBIG5_Unicode_MAP.Add (int.Parse (lTokens[0].Substring (2), NumberStyles.HexNumber), int.Parse (lTokens[1].Substring (2), NumberStyles.HexNumber));
            }
            catch (Exception)
            {
                continue; // No mapping
            }
        }
    }

    public static string ToUni (Stream _str)
    {
        StringBuilder _StringBuilder = new StringBuilder ();
        byte[] big5Buffer = new byte[2];

        int input;
        while ((input = _str.ReadByte ()) != -1)
        {

            if (input > 0x81 && big5Buffer[0] == 0) //lead byte of big 5
            {
                big5Buffer[0] = (byte)input;
            }
            else if (big5Buffer[0] != 0)
            {
                big5Buffer[1] = (byte)input;
                int Big5Char = (big5Buffer[0] << 8) + big5Buffer[1];
                try
                {
                    int UTF8Char = mBIG5_Unicode_MAP[Big5Char];
                    _StringBuilder.Append ((char)UTF8Char);
                }
                catch (Exception)
                {

                    _StringBuilder.Append ((char)mBIG5_Unicode_MAP[0xA148]); // No mapping, use replacement character
                }

                big5Buffer = new byte[2];
            }
            else
            {
                _StringBuilder.Append ((char)input); // ASCII character
            }
        }
        return _StringBuilder.ToString ();
    }
}

2012年3月20日 星期二

windows phone 7 模擬器 右邊的文字

參考:http://msdn.microsoft.com/en-us/library/ff967560(v=vs.92).aspx

CounterDescription
Composition Thread Frame Rate
This value refers to the rate at which the screen is updated. It also represents how often supported animations driven by a storyboard are updated. This value should be as close to 60 as possible. Application performance begins to degrade when this value is below 30. The text in this counter is red when displaying a value below 30.
UI Thread Frame Rate
This value refers to the rate at which the UI thread is running. The UI thread drives input, per-frame callbacks, and any other drawing not handled by the composition thread. The larger this value, the more responsive your application should be. Typically this value should be above 20 to provide an acceptable response time to user input. The text in this counter is red when displaying a value below 15.
Texture Memory Usage
This value represents the video memory and system memory copies of textures being used in the application. This is not a general memory counter for the application, but represents only memory that surfaces use.
Surface Counter
This value provides a raw count of the explicit surfaces being passed to the GPU for processing. The biggest contributor to this number is automatic or developer-cached elements.
Intermediate Surface Counter
This value represents the implicit surfaces generated as a result of cached surfaces. These surfaces are created in-between UI elements so that the application can accurately maintain the Z-order of elements in the UI.
Fill Rate Counter
This value represents the number of pixels being painted per frame in terms of screens. A value of 1 represents 480 x 800 pixels. The recommended value is about 2.5. The text in this counter turns red when displaying a value above 3.






2012年3月19日 星期一

查看APP的 Memory Usage

參考: http://msdn.microsoft.com/en-us/library/ff941122(v=VS.92).aspx

從DeviceStatus中 可獲得一些硬體的資訊
例如: 記憶體,電源..等等

總記憶體
Microsoft.Phone.Info.DeviceStatus.DeviceTotalMemory.ToString()
APP占用最多的記憶體
Microsoft.Phone.Info.DeviceStatus.ApplicationPeakMemoryUsage.ToString()
APP目前占用的記憶體
Microsoft.Phone.Info.DeviceStatus.ApplicationCurrentMemoryUsage.ToString()

2012年3月15日 星期四

Yield in C#


http://www.ytechie.com/2009/02/using-c-yield-for-readability-and-performance.html 

很棒的一篇文章, 利用yield 增加了變通性 讓使用者可以取得自己所需要的返回值

2012年3月13日 星期二

頁面切換動畫 TransitionService

以下是官方的Sample

<toolkit:TransitionService.NavigationInTransition>
    <toolkit:NavigationInTransition>
        <toolkit:NavigationInTransition.Backward>
            <toolkit:TurnstileTransition Mode="BackwardIn"/>
        </toolkit:NavigationInTransition.Backward>
        <toolkit:NavigationInTransition.Forward>
            <toolkit:TurnstileTransition Mode="ForwardIn"/>
        </toolkit:NavigationInTransition.Forward>
    </toolkit:NavigationInTransition>
</toolkit:TransitionService.NavigationInTransition>
<toolkit:TransitionService.NavigationOutTransition>
    <toolkit:NavigationOutTransition>
        <toolkit:NavigationOutTransition.Backward>
            <toolkit:TurnstileTransition Mode="BackwardOut"/>
        </toolkit:NavigationOutTransition.Backward>
        <toolkit:NavigationOutTransition.Forward>
            <toolkit:TurnstileTransition Mode="ForwardOut"/>
        </toolkit:NavigationOutTransition.Forward>
    </toolkit:NavigationOutTransition>
</toolkit:TransitionService.NavigationOutTransition>

有一點要特別注意就是 App.xaml.cs
RootFrame = new PhoneApplicationFrame();
要改為
RootFrame = new TransitionFrame();
不然會沒效果

如果要重複使用 可在Resource中宣告Style

2012年3月12日 星期一

Z-order In WP7

無意中發現 windows phone中 調整z order的方法 數字越大越上層
1. in xaml
       <Grid Name="cMaca" Canvas.ZIndex="100">
2. code-behind
      cMaca.SetValue (Canvas.ZIndexProperty, 100);

2012年3月7日 星期三

改變 ApplicationBar 的 IconButton

在code-behide中調用 會產生NullReferenceException
那要怎麼動態更改裡面的屬性呢?

其實PhoneApplicationPage中 有封裝一個ApplicationBar可以直接調用

那如果要改變裡面ApplicationBarIconButton的屬性呢?
這時候會發現ApplicationBar.Buttons不能直接Select裡面的ApplicationBarIconButton...囧
那怎麼解決呢?

方法一: 利用event中 回傳的 sender 轉型為 ApplicationBarIconButton
方法二: 利用ApplicationBar.Buttons 裡面的remove 和 insert
方法三: 直接在code-behide中定義ApplicationBar


方法二 code:
ApplicationBarIconButton _Button = new ApplicationBarIconButton (new Uri ("/x.png", UriKind.Relative));
 _Button.Click += new EventHandler (IconClick);
 _Button.Text = "xxx";
ApplicationBar.Buttons.RemoveAt (0);
ApplicationBar.Buttons.Insert (0, _Button);


Lambda Expressions

好用的東西~
http://msdn.microsoft.com/en-us/library/bb397687.aspx