2013年12月19日木曜日

Sublime Text 2 のプラグインで Toggle Comment を実装する

1. AAAPackageDev を Sublime Text に入れる
  • https://bitbucket.org/guillermooo/aaapackagedev/downloads から AAAPackageDev.sublime-package をダウンロードする
  • AAAPackageDev.sublime-package を Sublime Text の Installed Packages ([Preferences] - [Browse Packages...] から開くフォルダの一つ上の階層にある)に入れる
  • Sublime Text を再起動する


2. Package を作成する

作成する Syntax Definition に対応するパッケージがない場合は

[Tools] - [Packages] - [Package Development] - [New Packages...]

を選択し、パッケージ名を入力して Enter を押す



3. Comments Definition を作成する
  • <lang_name>.JSON-tmPreferences というファイル名で Packages/User フォルダーか、対応するパッケージフォルダに保存する
    1. "name""Comments",  
    2.   "scope""source.ts",  
    3.   "settings": {  
    4.    "shellVariables" : [  
    5.     {  
    6.      "name""TM_COMMENT_START",  
    7.      "value""// "  
    8.     },  
    9.     {  
    10.      "name""TM_COMMENT_START_2",  
    11.      "value""/*"  
    12.     },  
    13.     {  
    14.      "name""TM_COMMENT_END_2",  
    15.      "value""*/"  
    16.     }  
    17.    ]  
    18.   },  
    19.   "uuid""38232be9-44f1-49fd-91d4-85f5884fb298"  
    20. }  
  • "name" : "Comments" にする(別でもいいような気もするが)
  • "scope" : 対応する .tmLanguage の scopeName の値を使う
  • TM_COMMENT_START はシングルラインコメント、[Edit] - [Comment] - [Toggle Comment] に対応する
  • TM_COMMENT_START_2 はブロックコメントの開始、TM_COMMENT_END_2 はブロックコメントの終わり、[Edit] - [Comment] - [Toggle Block Comment] に対応する
  • ブロックコメントがない場合、TM_COMMENT_START_2とTM_COMMENT_END_2を両方省略することができる


4. .tmPreferences ファイルに変換する
  • [Tools] - [Build System] - [JSON to Property List] を選択
  • F7(または [Tools] - [Build])を押すと .JSON-tmPreferences ファイルと同じディレクトリに .tmPreferences ファイルができる
  • Sublime Text を再起動する




Sublime Text 2 用 ReVIEW プラグインでは [Edit] - [Comment] - [Toggle Comment] で先頭に #@# が挿入されるようにしました!



2013年12月9日月曜日

Android Javaコードで dp 単位を px 単位に変換する

1. DisplayMetrics を使う
  1. // 8dp に相当する px 値を取得  
  2. DisplayMetrics metrics = getResources().getDisplayMetrics();  
  3. int padding = (int) (metrics.density * 8);  


2. TypedValue.applyDimension() を使う
  1. // 8dp に相当する px 値を取得  
  2. int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,   
  3.                                               8,   
  4.                                               getResources().getDisplayMetrics());  


2013年12月2日月曜日

ActionBar の Overflow Menu の selector の色を変える

Android UI Cookbook for 4.0 で紹介した方法だと、適用する selector が不透明の場合はいいのですが、半透明の場合問題が起こります。

以下は、Android UI Cookbook for 4.0 で紹介した方法(android:itemBackground を指定する方法)で、押したとき背景が半透明の赤になるようにした場合です。



赤とデフォルトの水色が混ざって、紫っぽくなってしまっています。
これは、半透明の赤の下にデフォルトの水色の selector も表示されているからです。

これを修正する方法は2つあります。
  • 1. android:itemBackground には何も指定せず、下の水色の selector を変更する
  • 2. android:itemBackground を指定して、下の水色の selector に透明を指定する
いずれにしろ、この水色の selector を変更しないといけません。
結論としては、android:listChoiceBackgroundIndicator を利用します。この属性は API Level 11 からですが、Support Library v7 の appcompat でも対応しています。

res/values/styles.xml
  1. <resources xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   
  3.     <style name="AppTheme" parent="android:Theme.Holo.Light">  
  4.         <item name="android:listChoiceBackgroundIndicator">@drawable/selector_dropdownlist</item>  
  5.     </style>  
  6.   
  7. </resources>  


ただし!なぜかベースのテーマを Theme.Holo.Light.DarkActionBar にすると、この設定が効きません!(Theme.Holo、Theme.Holo.Light は効く)
原因はまだ見つけてません。ぐぬぬ


2013.12.3 追記

原因&解決方法を見つけました!
Theme.Holo.Light.DarkActionBar でセットされている属性を一つずつ追加していったところ、
  1. <item name="android:actionBarWidgetTheme">@android:style/Theme.Holo</item>  
が原因だということがわかりました。Theme.Holo および Theme.Holo.Light ではこの属性には @null が指定されています。

この属性は ActionBarImpl クラスで利用されています。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/java/com/android/internal/app/ActionBarImpl.java#800
  1. 800     public Context getThemedContext() {  
  2. 801         if (mThemedContext == null) {  
  3. 802             TypedValue outValue = new TypedValue();  
  4. 803             Resources.Theme currentTheme = mContext.getTheme();  
  5. 804             currentTheme.resolveAttribute(com.android.internal.R.attr.actionBarWidgetTheme,  
  6. 805                     outValue, true);  
  7. 806             final int targetThemeRes = outValue.resourceId;  
  8. 807   
  9. 808             if (targetThemeRes != 0 && mContext.getThemeResId() != targetThemeRes) {  
  10. 809                 mThemedContext = new ContextThemeWrapper(mContext, targetThemeRes);  
  11. 810             } else {  
  12. 811                 mThemedContext = mContext;  
  13. 812             }  
  14. 813         }  
  15. 814         return mThemedContext;  
  16. 815     }  
そこで、Theme.Holo を継承し android:listChoiceBackgroundIndicator をセットしたテーマを別途用意し、android:actionBarWidgetTheme に指定するようにしたところうまくいきました。
  1. <resources xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   
  3.     <style name="AppThemeHolo" parent="android:Theme.Holo">  
  4.         <item name="android:listChoiceBackgroundIndicator">@drawable/selector_dropdownlist</item>  
  5.     </style>  
  6.       
  7.     <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">  
  8.         <item name="android:listChoiceBackgroundIndicator">@drawable/selector_dropdownlist</item>  
  9.         <item name="android:actionBarWidgetTheme">@style/AppThemeHolo</item>  
  10.     </style>  
  11.   
  12. </resources>  





■ 詳細解説

Overflow Menu は ListPopupWindow です。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/java/com/android/internal/view/menu/MenuPopupHelper.java#122
  1. 122     public boolean tryShow() {  
  2. 123         mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);  
  3. 124         mPopup.setOnDismissListener(this);  
  4. 125         mPopup.setOnItemClickListener(this);  
  5. 126         mPopup.setAdapter(mAdapter);  
  6. 127         mPopup.setModal(true);  
  7. 128   
  8. 129         View anchor = mAnchorView;  
  9. 130         if (anchor != null) {  
  10. 131             final boolean addGlobalListener = mTreeObserver == null;  
  11. 132             mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest  
  12. 133             if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this);  
  13. 134             anchor.addOnAttachStateChangeListener(this);  
  14. 135             mPopup.setAnchorView(anchor);  
  15. 136             mPopup.setDropDownGravity(mDropDownGravity);  
  16. 137         } else {  
  17. 138             return false;  
  18. 139         }  
  19. 140   
  20. 141         if (!mHasContentWidth) {  
  21. 142             mContentWidth = measureContentWidth();  
  22. 143             mHasContentWidth = true;  
  23. 144         }  
  24. 145   
  25. 146         mPopup.setContentWidth(mContentWidth);  
  26. 147         mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);  
  27. 148         mPopup.show();  
  28. 149         mPopup.getListView().setOnKeyListener(this);  
  29. 150         return true;  
  30. 151     }  
ListPopupWindow には setListSelector() というメソッドが用意されています。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/java/android/widget/ListPopupWindow.java
  1.     350     public void setListSelector(Drawable selector) {  
  2.     351         mDropDownListHighlight = selector;  
  3.     352     }  
  4. ...  
  5.     971     private int buildDropDown() {  
  6.    1015     private int buildDropDown() {  
  7.    1016         ViewGroup dropDownView;  
  8.    1017         int otherHeights = 0;  
  9.    1018   
  10.    1019         if (mDropDownList == null) {  
  11.    1020             Context context = mContext;  
  12.    1021   
  13.    1022             /** 
  14.    1023              * This Runnable exists for the sole purpose of checking if the view layout has got 
  15.    1024              * completed and if so call showDropDown to display the drop down. This is used to show 
  16.    1025              * the drop down as soon as possible after user opens up the search dialog, without 
  17.    1026              * waiting for the normal UI pipeline to do it's job which is slower than this method. 
  18.    1027              */  
  19.    1028             mShowDropDownRunnable = new Runnable() {  
  20.    1029                 public void run() {  
  21.    1030                     // View layout should be all done before displaying the drop down.  
  22.    1031                     View view = getAnchorView();  
  23.    1032                     if (view != null && view.getWindowToken() != null) {  
  24.    1033                         show();  
  25.    1034                     }  
  26.    1035                 }  
  27.    1036             };  
  28.    1037   
  29.    1038             mDropDownList = new DropDownListView(context, !mModal);  
  30.    1039             if (mDropDownListHighlight != null) {  
  31.    1040                 mDropDownList.setSelector(mDropDownListHighlight);  
  32.    1041             }  
  33. ...  
しかし、MenuPopupHelper では、setListSelector() を呼んでくれていません。

ListPopupWindow 内のリストは、DropDownListView です。 このクラスは ListPopupWindow の内部クラスです。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/java/android/widget/ListPopupWindow.java#1445
  1. 1445         public DropDownListView(Context context, boolean hijackFocus) {  
  2. 1446             super(context, null, com.android.internal.R.attr.dropDownListViewStyle);  
  3. 1447             mHijackFocus = hijackFocus;  
  4. 1448             // TODO: Add an API to control this  
  5. 1449             setCacheColorHint(0); // Transparent, since the background drawable could be anything.  
  6. 1450         }  
ここでは com.android.internal.R.attr.dropDownListViewStyle を defStyleAttr として渡しています。

よって、android:dropDownListViewStyle を指定すればいいということです。Holo テーマでどのようなスタイルになっているか見てみましょう。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/res/res/values/themes.xml
  1.  906     <style name="Theme.Holo">  
  2. 1087         <item name="dropDownListViewStyle">@android:style/Widget.Holo.ListView.DropDown</item>  
  3. 1214     </style>  
  4. 1221     <style name="Theme.Holo.Light" parent="Theme.Light">  
  5. 1402         <item name="dropDownListViewStyle">@android:style/Widget.Holo.ListView.DropDown</item>  
  6. 1529     </style>  
Theme.Holo も Theme.Holo.Light も @android:style/Widget.Holo.ListView.DropDown がセットされています。

Widget.Holo.ListView.DropDown は Widget.Holo.ListView と同じで、Widget.Holo.ListView では android:divider として ?android:attr/listDivider を、android:listSelector として ?android:attr/listChoiceBackgroundIndicator をセットしています。
  1. 1649     <style name="Widget.Holo.ListView.DropDown">  
  2. 1650     </style>  
  3. 1715     <style name="Widget.Holo.ListView" parent="Widget.ListView">  
  4. 1716         <item name="android:divider">?android:attr/listDivider</item>  
  5. 1717         <item name="android:listSelector">?android:attr/listChoiceBackgroundIndicator</item>  
  6. 1718     </style>  
よって、android:listChoiceBackgroundIndicator に変更したい selector を指定すればいいということになります。



2013年12月1日日曜日

Espresso で Navigation Drawer を開閉する(DIを使わない編)

Navigation Drawer を開閉するには android.R.id.home ボタンをタップすればいいので、
  1. public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {  
  2.   
  3.     public MainActivityTest() {  
  4.         super(MainActivity.class);  
  5.     }  
  6.   
  7.     @Override  
  8.     public void setUp() throws Exception {  
  9.         super.setUp();  
  10.         // Espresso will not launch our activity for us, we must launch it via  
  11.         // getActivity().  
  12.         getActivity();  
  13.     }  
  14.   
  15.     public void testDrawerOpen() {  
  16.         // Drawer open  
  17.         onView(withId(android.R.id.home)).perform(click());  
  18.         // Click Settings  
  19.         onView(withId(R.id.settings)).perform(click());  
  20.     }  
  21. }  
で OK そうです(R.id.settings は Navigation Drawer 内のボタン)。

ところが、これはテストに失敗します。
onView(withId(R.id.settings)).perform(click());
のところで、そんな Id の View は見つからないと言われてしまいます。

原因は、Navigation Drawer が開き終わる前に View を探そうとするからです。

そこで、Navigation Drawer が開き(または閉じ)はじめてから、閉じる(または開く)まで、 Espresso に今は Idle 状態じゃないと伝えるようにします。

まず、IdlingResource インタフェースを実装したクラスのインスタンスを用意し、Espresso.registerIdlingResources()で登録します。

IdlingResource を実装したクラスとして、CountingIdlingResource が用意されています。
このクラスは内部でカウンターを持っていて、increment() と decrement() でカウンターの値を変え、カウンターが 0 のときが Idle 状態として Espresso に伝えられます。

Navigation Drawer を実現している DrawerLayout クラスの DrawerListener.onDrawerStateChanged() を利用して、カウンターの値を変えるようにします。

そのため、テスト対象の Activity に口を用意しないといけません。
  1. public class MainActivity extends ActionBarActivity implements DrawerListener {  
  2.   
  3.     private DrawerLayout mDrawerLayout;  
  4.     private View mDrawerContainer;  
  5.     private ActionBarDrawerToggle mDrawerToggle;  
  6.   
  7.     private DrawerFragment mDrawerFragment;  
  8.   
  9.     /** 
  10.      * Espresso で Drawer を開くため 
  11.      */  
  12.     public interface DrawerStateListener {  
  13.         public void onDrawerStateChanged(int newState);  
  14.     }  
  15.   
  16.     private DrawerStateListener mDrawerStateListener;  
  17.   
  18.     public void setDrawerListener(DrawerStateListener l) {  
  19.         mDrawerStateListener = l;  
  20.     }  
  21.   
  22.     public DrawerStateListener getDrawerListener() {  
  23.         return mDrawerStateListener;  
  24.     }  
  25.     /** 
  26.      *  
  27.      */  
  28.   
  29.     @Override  
  30.     protected void onCreate(Bundle savedInstance) {  
  31.         super.onCreate(savedInstance);  
  32.         setContentView(R.layout.activity_main);  
  33.   
  34.         mDrawerFragment = (DrawerFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_drawer);  
  35.   
  36.         mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);  
  37.         mDrawerContainer = findViewById(R.id.left_drawer);  
  38.   
  39.         mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer,  
  40.                 R.string.drawer_open, R.string.drawer_close) {  
  41.   
  42.             @Override  
  43.             public void onDrawerClosed(View drawerView) {  
  44.                 supportInvalidateOptionsMenu();  
  45.                 super.onDrawerClosed(drawerView);  
  46.             }  
  47.   
  48.             @Override  
  49.             public void onDrawerOpened(View drawerView) {  
  50.                 supportInvalidateOptionsMenu();  
  51.                 super.onDrawerOpened(drawerView);  
  52.             }  
  53.   
  54.             @Override  
  55.             public void onDrawerStateChanged(int newState) {  
  56.                 if (mDrawerStateListener != null) {  
  57.                     mDrawerStateListener.onDrawerStateChanged(newState);  
  58.                 }  
  59.                 super.onDrawerStateChanged(newState);  
  60.             }  
  61.         };  
  62.   
  63.         mDrawerLayout.setDrawerListener(mDrawerToggle);  
  64.   
  65.         getSupportActionBar().setDisplayHomeAsUpEnabled(true);  
  66.         getSupportActionBar().setHomeButtonEnabled(true);  
  67.     }  
  68.   
  69.     ...  
  70. }  
Activity に DrawerStateListener という口を用意しました。
この DrawerStateListener を実装した DrawerStateListenerImpl クラスを用意し、onDrawerStateChanged(int newState) で newState の値に応じて increment(), decrement() します。 このテストでは Navigation Drawer 部分をドラッグしないので DrawerLayout.STATE_DRAGGING は無いと思って簡略化しています。

setUp() の中で getActivity() で取得した Activity に対して DrawerStateListenerImpl のインスタンスを差し込み、registerIdlingResources() で DrawerStateListenerImpl で参照している CountingIdlingResource のインスタンスを登録しています。
  1. public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {  
  2.   
  3.     public MainActivityTest() {  
  4.         super(MainActivity.class);  
  5.     }  
  6.   
  7.     private class DrawerStateListenerImpl implements DrawerStateListener {  
  8.         private final DrawerStateListener realDrawerListener;  
  9.         private final CountingIdlingResource mIdlingResource;  
  10.   
  11.         private DrawerStateListenerImpl(DrawerStateListener l, CountingIdlingResource idlingResource) {  
  12.             this.realDrawerListener = l;  
  13.             this.mIdlingResource = checkNotNull(idlingResource);  
  14.         }  
  15.   
  16.         @Override  
  17.         public void onDrawerStateChanged(int newState) {  
  18.             // ドラッグしないので  
  19.             if (newState != DrawerLayout.STATE_IDLE) {  
  20.                 mIdlingResource.increment();  
  21.             } else {  
  22.                 mIdlingResource.decrement();  
  23.             }  
  24.   
  25.             if (realDrawerListener != null) {  
  26.                 realDrawerListener.onDrawerStateChanged(newState);  
  27.             }  
  28.         }  
  29.     }  
  30.   
  31.     @Override  
  32.     public void setUp() throws Exception {  
  33.         super.setUp();  
  34.         // Espresso will not launch our activity for us, we must launch it via  
  35.         // getActivity().  
  36.         MainActivity activity = getActivity();  
  37.         CountingIdlingResource countingResource = new CountingIdlingResource("DrawerCalls");  
  38.         activity.setDrawerListener(new DrawerStateListenerImpl(activity.getDrawerListener(), countingResource));  
  39.         registerIdlingResources(countingResource);  
  40.     }  
  41.   
  42.     public void testDrawerOpen() {  
  43.         // Drawer open  
  44.         onView(withId(android.R.id.home)).perform(click());  
  45.         // Click Settings  
  46.         onView(withId(R.id.settings)).perform(click());  
  47.     }  
  48. }  
このテストでは、ちゃんと R.id.settings ボタンがクリックされます。


Unable to execute dex: java.nio.BufferOverflowException.

[2013-12-01 12:14:18 - Dex Loader] Unable to execute dex: java.nio.BufferOverflowException. Check the Eclipse log for stack trace.

とか言われて調べていると、次の Issue に行き当たりました。

Issue 61710 - android - java.nio.BufferOverflowException When Building with 19 Build Tools - Android Open Source Project - Issue Tracker - Google Project Hosting:

Build Tool を 19.0.0 から 18.1.1 にしたらいいらしので、

Android SDK Manager を開いて
  • Android SDK Build-tools Rev. 19 を削除
  • Android SDK Build-tools Rev. 18.1.1 をインストール


エラーがでなくなりました!



2013年11月26日火曜日

Espresso で EditTextPreference に文字を入力する方法

Espresso で EditText に日本語を入力する方法」と「Espresso で Preference をクリックさせる」の応用です。

EditTextPreference はダイアログ内の EditText をコードから生成し、Id として com.android.internal.R.id.edit をセットしています。

http://tools.oesf.biz/android-4.4.0_r1.0/xref/frameworks/base/core/java/android/preference/EditTextPreference.java#53
  1. 45 public class EditTextPreference extends DialogPreference {  
  2. 46     /** 
  3. 47      * The edit text shown in the dialog. 
  4. 48      */  
  5. 49     private EditText mEditText;  
  6. 50   
  7. 51     private String mText;  
  8. 52   
  9. 53     public EditTextPreference(Context context, AttributeSet attrs, int defStyle) {  
  10. 54         super(context, attrs, defStyle);  
  11. 55   
  12. 56         mEditText = new EditText(context, attrs);  
  13. 57   
  14. 58         // Give it an ID so it can be saved/restored  
  15. 59         mEditText.setId(com.android.internal.R.id.edit);  
  16. 60   
  17. 61         /* 
  18. 62          * The preference framework and view framework both have an 'enabled' 
  19. 63          * attribute. Most likely, the 'enabled' specified in this XML is for 
  20. 64          * the preference framework, but it was also given to the view framework. 
  21. 65          * We reset the enabled state. 
  22. 66          */  
  23. 67         mEditText.setEnabled(true);  
  24. 68     }  
internal なので Id を指定する方法は使えません。そこで、isAssignableFrom()を使います。(withClassName()でも実現できます)
  1. public void testEditTextPreference() {  
  2.     // EditTextPreference をクリック  
  3.     onData(withPreferenceKey("edit_text_pref1")).perform(click());  
  4.     onView(isAssignableFrom(EditText.class)).perform(clearText(), new InputTextAction("エスプレッソよりカフェラテ派"));  
  5.     onView(withText("OK")).perform(click());  
  6.   
  7.     // 例えば入力値が summary に表示されるような実装になっているなら、それをチェックできる  
  8.     onData(withPreferenceKey("edit_text_pref1"))  
  9.         .onChildView(withId(android.R.id.summary))  
  10.         .check(matches(withText("エスプレッソよりカフェラテ派")));  
  11. }  



Espresso で EditText に日本語を入力する方法

Espresso には、テキストをタイプする ViewActions.typeText() というメソッドが用意されています。
このメソッドは、引数で渡されたテキストの各文字に対応する KeyCode を入力するものです。
そのため、typeText("日本語") としても"日本語"は入力されませんし、ソフトキーボードが日本語キーボードのときに typeText("andoroido") とすると、"あんどろいど" と入力されます。
また困ったことに、ソフトキーボードが日本語キーボードのときに typeText("12345") とすると、全角で入力されます。orz


日本語を入力するには、setText() で直接セットするしかありません。
そのための ViewAction を実装したクラスを用意しました。

  1.     public void testInputJapanese() {  
  2.         onView(R.id.editText1).perform(clearText(), new InputTextAction("日本語"));  
  3.         onView(R.id.editText1).check(matches(withText("日本語")));  
  4.     }  
  5.   
  6.     public final class InputTextAction implements ViewAction {  
  7.         private final String mText;  
  8.   
  9.         public InputTextAction(String text) {  
  10.             checkNotNull(text);  
  11.             mText = text;  
  12.         }  
  13.   
  14.         @SuppressWarnings("unchecked")  
  15.         @Override  
  16.         public Matcher<view> getConstraints() {  
  17.             return allOf(isDisplayed(), isAssignableFrom(EditText.class));  
  18.         }  
  19.   
  20.         @Override  
  21.         public void perform(UiController uiController, View view) {  
  22.             ((EditText) view).setText(mText);  
  23.         }  
  24.   
  25.         @Override  
  26.         public String getDescription() {  
  27.             return "set text";  
  28.         }  
  29.     }  
  30. </view>  



ちなみに typeText() の実体は TypeTextAction クラスです。

ViewActions.java
  1. public final class ViewActions {  
  2.   ...  
  3.   
  4.   public static ViewAction typeText(String stringToBeTyped) {  
  5.     return new TypeTextAction(stringToBeTyped);  
  6.   }  
  7. }  
こちらでは UiController の injectString() を利用しています。また、SearchView にも入力できるみたいです。

TypeTextAction.java
  1. public final class TypeTextAction implements ViewAction {  
  2.   private static final String TAG = TypeTextAction.class.getSimpleName();  
  3.   private final String stringToBeTyped;  
  4.   
  5.   /** 
  6.    * Constructs {@link TypeTextAction} with given string. If the string is empty it results in no-op 
  7.    * (nothing is typed). 
  8.    * 
  9.    * @param stringToBeTyped String To be typed by {@link TypeTextAction} 
  10.    */  
  11.   public TypeTextAction(String stringToBeTyped) {  
  12.     checkNotNull(stringToBeTyped);  
  13.     this.stringToBeTyped = stringToBeTyped;  
  14.   }  
  15.   
  16.   @SuppressWarnings("unchecked")  
  17.   @Override  
  18.   public Matcher<view> getConstraints() {  
  19.     Matcher<view> matchers = allOf(isDisplayed());  
  20.     if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {  
  21.        return allOf(matchers, supportsInputMethods());  
  22.     } else {  
  23.        // SearchView does not support input methods itself (rather it delegates to an internal text  
  24.        // view for input).  
  25.        return allOf(matchers, anyOf(supportsInputMethods(), isAssignableFrom(SearchView.class)));  
  26.     }  
  27.   }  
  28.   
  29.   @Override  
  30.   public void perform(UiController uiController, View view) {  
  31.     // No-op if string is empty.  
  32.     if (stringToBeTyped.length() == 0) {  
  33.       Log.w(TAG, "Supplied string is empty resulting in no-op (nothing is typed).");  
  34.       return;  
  35.     }  
  36.   
  37.     // Perform a click.  
  38.     new GeneralClickAction(Tap.SINGLE, GeneralLocation.CENTER, Press.PINPOINT)  
  39.         .perform(uiController, view);  
  40.     uiController.loopMainThreadUntilIdle();  
  41.   
  42.     try {  
  43.       if (!uiController.injectString(stringToBeTyped)) {  
  44.         Log.e(TAG, "Failed to type text: " + stringToBeTyped);  
  45.         throw new PerformException.Builder()  
  46.           .withActionDescription(this.getDescription())  
  47.           .withViewDescription(HumanReadables.describe(view))  
  48.           .withCause(new RuntimeException("Failed to type text: " + stringToBeTyped))  
  49.           .build();  
  50.       }  
  51.     } catch (InjectEventSecurityException e) {  
  52.       Log.e(TAG, "Failed to type text: " + stringToBeTyped);  
  53.       throw new PerformException.Builder()  
  54.         .withActionDescription(this.getDescription())  
  55.         .withViewDescription(HumanReadables.describe(view))  
  56.         .withCause(e)  
  57.         .build();  
  58.     }  
  59.   }  
  60.   
  61.   @Override  
  62.   public String getDescription() {  
  63.     return "type text";  
  64.   }  
  65. }  
  66. </view></view>  
UiController はインタフェースで、実装クラスは UiControllerImpl.java です。

UiControllerImpl.java
  1. @Override  
  2. public boolean injectString(String str) throws InjectEventSecurityException {  
  3.   checkNotNull(str);  
  4.   checkState(Looper.myLooper() == mainLooper, "Expecting to be on main thread!");  
  5.   initialize();  
  6.   
  7.   // No-op if string is empty.  
  8.   if (str.length() == 0) {  
  9.     Log.w(TAG, "Supplied string is empty resulting in no-op (nothing is typed).");  
  10.     return true;  
  11.   }  
  12.   
  13.   boolean eventInjected = false;  
  14.   KeyCharacterMap keyCharacterMap = getKeyCharacterMap();  
  15.   
  16.   // TODO(user): Investigate why not use (as suggested in javadoc of keyCharacterMap.getEvents):  
  17.   // http://developer.android.com/reference/android/view/KeyEvent.html#KeyEvent(long,  
  18.   // java.lang.String, int, int)  
  19.   KeyEvent[] events = keyCharacterMap.getEvents(str.toCharArray());  
  20.   checkNotNull(events, "Failed to get events for string " + str);  
  21.   Log.d(TAG, String.format("Injecting string: \"%s\"", str));  
  22.   
  23.   for (KeyEvent event : events) {  
  24.     checkNotNull(event, String.format("Failed to get event for character (%c) with key code (%s)",  
  25.         event.getKeyCode(), event.getUnicodeChar()));  
  26.   
  27.     eventInjected = false;  
  28.     for (int attempts = 0; !eventInjected && attempts < 4; attempts++) {  
  29.       attempts++;  
  30.   
  31.       // We have to change the time of an event before injecting it because  
  32.       // all KeyEvents returned by KeyCharacterMap.getEvents() have the same  
  33.       // time stamp and the system rejects too old events. Hence, it is  
  34.       // possible for an event to become stale before it is injected if it  
  35.       // takes too long to inject the preceding ones.  
  36.       event = KeyEvent.changeTimeRepeat(event, SystemClock.uptimeMillis(), 0);  
  37.       eventInjected = injectKeyEvent(event);  
  38.     }  
  39.   
  40.     if (!eventInjected) {  
  41.       Log.e(TAG, String.format("Failed to inject event for character (%c) with key code (%s)",  
  42.           event.getUnicodeChar(), event.getKeyCode()));  
  43.       break;  
  44.     }  
  45.   }  
  46.   
  47.   return eventInjected;  
  48. }  



Espresso で Preference をクリックさせる

Matcher 書かないとダメっぽかったです。
PreferenceMatcher が用意されていたので利用しました。
  1. import static com.google.common.base.Preconditions.checkNotNull;  
  2. ...  
  3.   
  4. public class EspressoTest extends ActivityInstrumentationTestCase2<MainPreferenceActivity> {  
  5.   
  6.     public EspressoTest() {  
  7.         super(MainPreferenceActivity.class);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void setUp() throws Exception {  
  12.         super.setUp();  
  13.         // Espresso will not launch our activity for us, we must launch it via  
  14.         // getActivity().  
  15.         getActivity();  
  16.     }  
  17.   
  18.     // Preference のキーを指定して、対応するビューをクリックする  
  19.     public void testPreference() {  
  20.         onData(withPreferenceKey("pref-key")).perform(click());  
  21.     }  
  22.   
  23.     public static Matcher<Object> withPreferenceKey(final Matcher<Preference> preferenceMatcher) {  
  24.         checkNotNull(preferenceMatcher);  
  25.         return new BoundedMatcher<Object, Preference>(Preference.class) {  
  26.   
  27.             @Override  
  28.             public void describeTo(Description description) {  
  29.                 description.appendText("with preference key: ");  
  30.                 preferenceMatcher.describeTo(description);  
  31.             }  
  32.   
  33.             @Override  
  34.             protected boolean matchesSafely(Preference pref) {  
  35.                 return preferenceMatcher.matches(pref);  
  36.             }  
  37.         };  
  38.     }  
  39.   
  40.     public static Matcher<Object> withPreferenceKey(String expectedText) {  
  41.         checkNotNull(expectedText);  
  42.         return withPreferenceKey(PreferenceMatchers.withKey(expectedText));  
  43.     }  
  44. }  


応用で、Preference をクリック → なんかする → summary が適切な値になっていることをチェック
  1. public void testPreference() {  
  2.     // Preference をクリック  
  3.     onData(withPreferenceKey("pref-key")).perform(click());  
  4.   
  5.     // クリック先でごにょごにょ  
  6.   
  7.     // summary が適切な値になっていることをチェック  
  8.     // summary の Id が android.R.id.summary であることを利用  
  9.     onData(withPreferenceKey("pref-key"))  
  10.         .onChildView(withId(android.R.id.summary))  
  11.         .check(matches(withText("correct summary value")));  
  12. }  



2013年11月21日木曜日

Android で mockito を使う : すでにあるインスタンスから mock を作る

忘れるので、メモ。

Mockito.spy() を使う。

mockito と Espresso を組み合わせて使う場合、ActivityInstrumentationTestCase2 の setActivity() を Override してモック化した Activity を super.setActivity() に渡すようにしても、UIの操作が実際に行われるのはモック化前の生のActivityインスタンスに対してでした。 なので、ActivityInstrumentationTestCase2 の対象の Activity のメソッド呼び出しを mockito で検証するのは無理っぽいです。。。残念。。。


Android UI Testing framework の Espresso を使う

とりあえず、android-test-kit : Espresso の動画を見ましょう。

以下では Eclipse での設定方法を紹介します。
Android Studio での設定方法は Espresso のプロジェクトページ(上記のリンク)にあるので読んでください。

1. Developer options の設定

アニメーションを Off にしましょう。

設定(Settings) → 開発者向けオプション(Developer options)→
以下の3つを全て「アニメーションオフ(Animation off)」にする
  • ウィンドウアニメスケール (Window animation scale)
  • トランジションアニメスケール(Transition animation scale)
  • Animator再生時間スケール(Animator duration scale)


コードからやる方法


2. Espresso をテストプロジェクトに追加する

Espresso には、依存ライブラリとかも含めて1つの jar になっている standalone 版と、依存ライブラリが別になっている dependencies 版があります。

mockito と一緒に使う場合は、hamcrest がかぶってエラーになるので、dependencies 版を使います。

standalone 版を使う場合:git clone するなり、zip をダウンロードするなりして、 espresso-1.0-SNAPSHOT-bundled.jar を取得して、テストプロジェクトの libs フォルダに追加します。

dependencies 版を使う場合: dependencies 版 にある jar を全部 libs フォルダに入れます。
mockito (mockito-all-1.9.5.jar) と一緒に使う場合は、hamcrest-core-1.1.jar と hamcrest-integration-1.1.jar は libs に入れないでください。



テストプロジェクトの AndroidManifest.xml に
  1. <instrumentation  
  2.   android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"  
  3.   android:targetPackage="$YOUR_TARGET_APP_PACKAGE"/>  
を追加します。 AndroidManifest.xml の例
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.espresso.test"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="19" />  
  10.   
  11.     <application>  
  12.         <uses-library android:name="android.test.runner" />  
  13.     </application>  
  14.   
  15.     <instrumentation  
  16.         android:name="com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner"  
  17.         android:targetPackage="com.example.espresso" />  
  18.   
  19. </manifest>  
ウィザードから Android Test Project を作ると、android.test.InstrumentationTestRunner の instrumentation タグが作られますが、消しても大丈夫です。
  1. <instrumentation  
  2.     android:name="android.test.InstrumentationTestRunner"  
  3.     android:targetPackage="com.example.espresso" />  


GoogleInstrumentationTestRunner を介してテストが走るように Eclipse を設定します。
Eclipse の [Run] - [Run Configurations...]を選択



Run all tests in the selected project, or package にチェックして、 Instrumetation runner: に com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner を選択して Apply をクリックします。



* クラス単体を対象とした場合(Run a single Test をチェック)、Instrumetation runner: に com.google.android.apps.common.testing.testrunner.GoogleInstrumentationTestRunner を選択すると、 The instrumentation runner must be of type android.test.InstrumentationTestRunner とエラーが出て怒られます。
Espresso ではクラス単体でテストを走らせることはできないってことなのかしら?

Espresso はいくつかの解析データを収集しています。
収集されたくない場合は、disableAnalytics という引数に true を指定して GoogleInstrumentationTestRunner に渡すことでオプトアウトすることができるとドキュメントには書いてあるのですが、方法がよくわかりませんでした。。。


3. Espresso を使う

例として、ログイン画面(MainActivity)でIDとパスワードを入力してボタンを押すと、Welcome画面(MainActivity2)に遷移するアプリを用意しました。
  1. public class MainActivity extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main);  
  7.   
  8.         final EditText idView = (EditText) findViewById(R.id.editText1);  
  9.         final EditText passView = (EditText) findViewById(R.id.editText2);  
  10.         final TextView statusView = (TextView) findViewById(R.id.textView3);  
  11.   
  12.         findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {  
  13.   
  14.             @Override  
  15.             public void onClick(View v) {  
  16.                 statusView.setText("");  
  17.                 String id = idView.getText().toString();  
  18.                 if (TextUtils.isEmpty(id)) {  
  19.                     statusView.setText("IDが入力されていません");  
  20.                     return;  
  21.                 }  
  22.                 String pass = passView.getText().toString();  
  23.                 if (TextUtils.isEmpty(pass)) {  
  24.                     statusView.setText("Passwordが入力されていません");  
  25.                     return;  
  26.                 }  
  27.   
  28.                 if (check(id, pass)) {  
  29.                     Intent intent = new Intent(MainActivity.this, MainActivity2.class);  
  30.                     intent.putExtra("id", id);  
  31.                     startActivity(intent);  
  32.                 } else {  
  33.                     statusView.setText("IDとPasswordの組み合わせが違います");  
  34.                 }  
  35.             }  
  36.         });  
  37.     }  
  38.   
  39.     boolean check(String id, String pass) {  
  40.         // dummy  
  41.         return true;  
  42.     };  
  43. }  
ログイン画面(MainActivity)では、IDやパスワードが空の場合はステータス用のTextViewにメッセージが表示されます。
つまり
・ID入力用のEditTExtが空のときにステータス用のTextViewにメッセージが表示されるか
・Password入力用のEditTextが空のときにステータス用のTextViewにメッセージが表示されるか
をテストできます。



ログインできる場合は、Intentのextraにidを入れて、Welcome画面(MainActivity2)を開いています。
  1. public class MainActivity2 extends Activity {  
  2.   
  3.     @Override  
  4.     protected void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.activity_main2);  
  7.           
  8.         String id = getIntent().getStringExtra("id");  
  9.         TextView tv = (TextView) findViewById(R.id.textView1);  
  10.         tv.setText("ようこそ" + id + "さん");  
  11.     }  
  12. }  
Welcome画面(MainActivity2)では、渡されたidをTextView に表示しています。
ここでは、
・ログイン画面で入力されたIDがWelcome画面に表示されるか
をテストできます。




では、テストクラスを作っていきます。

Espresso, ViewActions, ViewMatchers, ViewAssertions, Matchers などの主要 static メソッドを import static で定義しておきましょう。
Espresso のドキュメントに載っているサンプルコードはみな import static した後のコードです。そのことを知ってないとコードをみてもよくわからないでしょう。
ドキュメントのコードをコピペするときにも不便なので、以下の import static をテストクラスにコピペしておきましょう。

  1. import static com.google.android.apps.common.testing.ui.espresso.Espresso.onData;  
  2. import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;  
  3. import static com.google.android.apps.common.testing.ui.espresso.Espresso.pressBack;  
  4. import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;  
  5. import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.closeSoftKeyboard;  
  6. import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;  
  7. import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;  
  8. import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;  
  9. import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;  
  10. import static org.hamcrest.Matchers.allOf;  
  11. import static org.hamcrest.Matchers.containsString;  
  12. import static org.hamcrest.Matchers.instanceOf;  
  13. import static org.hamcrest.Matchers.is;  


Espresso は Activity を起動してくれないので、setUp() で getActivity() を呼んで Activity を起動する必要があります。

  1. package com.example.espresso;  
  2.   
  3. import static com.google.android.apps.common.testing.ui.espresso.Espresso.onView;  
  4. import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.click;  
  5. import static com.google.android.apps.common.testing.ui.espresso.action.ViewActions.typeText;  
  6. import static com.google.android.apps.common.testing.ui.espresso.assertion.ViewAssertions.matches;  
  7. import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withId;  
  8. import static com.google.android.apps.common.testing.ui.espresso.matcher.ViewMatchers.withText;  
  9. import android.test.ActivityInstrumentationTestCase2;  
  10.   
  11. public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {  
  12.   
  13.     public MainActivityTest() {  
  14.         super(MainActivity.class);  
  15.     }  
  16.   
  17.     @Override  
  18.     public void setUp() throws Exception {  
  19.         super.setUp();  
  20.         // Espresso will not launch our activity for us, we must launch it via  
  21.         // getActivity().  
  22.         getActivity();  
  23.     }  
  24.       
  25.     public void testEmptyId() {  
  26.         // IDを空のままログインボタンをクリック  
  27.         onView(withId(R.id.button1)).perform(click());  
  28.         // ステータス用のTextViewにメッセージが表示されるかチェック  
  29.         onView(withId(R.id.textView3)).check(matches(withText("IDが入力されていません")));  
  30.     }  
  31.   
  32.     public void testEmptyPassword() {  
  33.         // IDを入力  
  34.         onView(withId(R.id.editText1)).perform(typeText("yanzm"));  
  35.         // Passwordを空のままログインボタンをクリック  
  36.         onView(withId(R.id.button1)).perform(click());  
  37.         // ステータス用のTextViewにメッセージが表示されるかチェック  
  38.         onView(withId(R.id.textView3)).check(matches(withText("Passwordが入力されていません")));  
  39.     }  
  40.       
  41.   
  42.     public void testLogin() {  
  43.         // IDを入力  
  44.         onView(withId(R.id.editText1)).perform(typeText("yanzm"));  
  45.         // Passwordを入力  
  46.         onView(withId(R.id.editText2)).perform(typeText("1234567890"));  
  47.         // ログインボタンをクリック  
  48.         onView(withId(R.id.button1)).perform(click());  
  49.         // Welcome画面に表示されるかチェック  
  50.         onView(withId(R.id.textView1)).check(matches(withText("ようこそyanzmさん")));  
  51.     }  
  52. }  


こんな感じです。

他にも、ListView や Spinner などの特定の行の View を指定するために使う onData() などがあります。


参考




2013年11月20日水曜日

Device Art Generator ではめ込み画像を作る

Android Developers に Device Art Generator という便利なものがあることに最近気づきました。



デイバス名の下にはめ込む画像のピクセルサイズが書かれています。
このサイズの画像をデバイス画像のところにドラッグ&ドロップします。
(サイズの違う画像だと怒られます)

・影
・画面の光沢

の有り無しを設定できるほか、回転させることもできます。

影あり・画面光沢あり


影なし・画面光沢あり


影なし・画面光沢なし


回転





2013年11月19日火曜日

Android Facebook SDK で share する

Facebook アプリは ACTION_SEND を受けとるくせに、Facebook に投稿してくれません。
ひどいです。ちゃんと処理しないなら ACTION_SEND 受け取らないでほしいです。。。

Facebook に投稿したければ Facebook SDK 使えよ、ということだそうです。
でもドキュメントがわちゃーでわかりにくかったので、自分ためにメモっておきます。



1. Facebook Apps を作る

https://developers.facebook.com/apps


右上の + Create New App から





2. Debug key の key hash を登録する

Debug key のパスワードは android
$[ keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
Enter keystore password:  android
pnw+gKvPF3Y+pP9nbguTOPw3s1g=




3. Facebook SDK for Android をダウンロードして展開する

https://developers.facebook.com/docs/android/

現在は v3.5.2





4. facebook-android-sdk-3.5.2/facebook/ を指定してインポートする



FacebookSDK の libs に含まれる android-support-v4.jar が古いので、新しいので上書きする。



5. 1.で指定したパッケージ名のアプリと Activity を作る





6. App ID を AndroidManifest.xml に宣言する

res/values/strings.xml
  1. <!--xml version="1.0" encoding="utf-8"?-->  
  2. <resources>  
  3.     <string name="app_id">APP_ID</string>  
  4. </resources>  
AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android" ... >  
  3.   
  4.     ...  
  5.   
  6.     <application ... >  
  7.   
  8.         ...  
  9.   
  10.         <meta-data   
  11.             android:value="@string/app_id"   
  12.             android:name="com.facebook.sdk.ApplicationId"/>  
  13.     </application>  
  14.   
  15. </manifest>  


7. FacebookSDK のライブラリプロジェクトを追加する





8. Activity に Share を実装する

ShareDialogBuilder を使う
  1. public class MainActivity extends Activity {  
  2.   
  3.     private UiLifecycleHelper uiHelper;  
  4.   
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.activity_main);  
  9.   
  10.         uiHelper = new UiLifecycleHelper(thisnew Session.StatusCallback() {  
  11.               
  12.             @Override  
  13.             public void call(Session session, SessionState state, Exception exception) {  
  14.                 Log.i("Activity""SessionState : " + state);  
  15.             }  
  16.         });  
  17.         uiHelper.onCreate(savedInstanceState);  
  18.   
  19.         findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {  
  20.   
  21.             @Override  
  22.             public void onClick(View v) {  
  23.                 share();  
  24.             }  
  25.         });  
  26.     }  
  27.   
  28.     private void share() {  
  29.         if (FacebookDialog.canPresentShareDialog(getApplicationContext(),  
  30.                 FacebookDialog.ShareDialogFeature.SHARE_DIALOG)) {  
  31.             try {  
  32.                 String name = "名前";  
  33.                 String url = "http://developer.android.com";  
  34.                 String description = "詳細";  
  35.   
  36.                 // Fragment で発行するときは setFragment() を呼ぶ  
  37.                 FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this).setDescription(description)  
  38.                         .setName(name).setLink(url).build();  
  39.                 uiHelper.trackPendingDialogCall(shareDialog.present());  
  40.             } catch (FacebookException e) {  
  41.                 Toast.makeText(this"Facebook でエラーが発生しました。", Toast.LENGTH_SHORT).show();  
  42.             }  
  43.         }  
  44.     }  
  45.   
  46.     @Override  
  47.     protected void onResume() {  
  48.         super.onResume();  
  49.         uiHelper.onResume();  
  50.     }  
  51.   
  52.     @Override  
  53.     protected void onSaveInstanceState(Bundle outState) {  
  54.         super.onSaveInstanceState(outState);  
  55.         uiHelper.onSaveInstanceState(outState);  
  56.     }  
  57.   
  58.     @Override  
  59.     public void onPause() {  
  60.         super.onPause();  
  61.         uiHelper.onPause();  
  62.     }  
  63.   
  64.     @Override  
  65.     public void onDestroy() {  
  66.         super.onDestroy();  
  67.         uiHelper.onDestroy();  
  68.     }  
  69.   
  70.     @Override  
  71.     protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  72.         super.onActivityResult(requestCode, resultCode, data);  
  73.   
  74.         uiHelper.onActivityResult(requestCode, resultCode, data, new FacebookDialog.Callback() {  
  75.             @Override  
  76.             public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {  
  77.                 Log.e("Activity", String.format("Error: %s", error.toString()));  
  78.             }  
  79.   
  80.             @Override  
  81.             public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {  
  82.                 Log.i("Activity""Success!");  
  83.             }  
  84.         });  
  85.     }  
  86. }  




9. Release Key の key hash を登録する

keytool -exportcert -alias <RELEASE_KEY_ALIAS> -keystore <RELEASE_KEY_PATH> | openssl sha1 -binary | openssl base64


10. Facebook Apps の設定の Sandbox Mode を Disabled にする







参考



Android Volley の NetworkImageView で Bitmap の最大サイズを指定する

Volley の NetworkImageView は便利なのですが、Bitmap のサイズを最適化してくれません。

NetworkImageView で画像のダウンロードを開始するのが loadImageIfNecessary() です。

https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/NetworkImageView.java
  1. public class NetworkImageView extends ImageView {  
  2.   
  3.     ...  
  4.   
  5.     /** Local copy of the ImageLoader. */  
  6.     private ImageLoader mImageLoader;  
  7.   
  8.     ...  
  9.   
  10.     public void setImageUrl(String url, ImageLoader imageLoader) {  
  11.         mUrl = url;  
  12.         mImageLoader = imageLoader;  
  13.         // The URL has potentially changed. See if we need to load it.  
  14.         loadImageIfNecessary(false);  
  15.     }  
  16.   
  17.     ...  
  18.   
  19.     /** 
  20.      * Loads the image for the view if it isn't already loaded. 
  21.      * @param isInLayoutPass True if this was invoked from a layout pass, false otherwise. 
  22.      */  
  23.     private void loadImageIfNecessary(final boolean isInLayoutPass) {  
  24.          
  25.         ...  
  26.   
  27.         // The pre-existing content of this view didn't match the current URL. Load the new image  
  28.         // from the network.  
  29.         ImageContainer newContainer = mImageLoader.get(mUrl,  
  30.                 new ImageListener() {  
  31.                     @Override  
  32.                     public void onErrorResponse(VolleyError error) {  
  33.                         if (mErrorImageId != 0) {  
  34.                             setImageResource(mErrorImageId);  
  35.                         }  
  36.                     }  
  37.   
  38.                     @Override  
  39.                     public void onResponse(final ImageContainer response, boolean isImmediate) {  
  40.                         // If this was an immediate response that was delivered inside of a layout  
  41.                         // pass do not set the image immediately as it will trigger a requestLayout  
  42.                         // inside of a layout. Instead, defer setting the image by posting back to  
  43.                         // the main thread.  
  44.                         if (isImmediate && isInLayoutPass) {  
  45.                             post(new Runnable() {  
  46.                                 @Override  
  47.                                 public void run() {  
  48.                                     onResponse(response, false);  
  49.                                 }  
  50.                             });  
  51.                             return;  
  52.                         }  
  53.   
  54.                         if (response.getBitmap() != null) {  
  55.                             setImageBitmap(response.getBitmap());  
  56.                         } else if (mDefaultImageId != 0) {  
  57.                             setImageResource(mDefaultImageId);  
  58.                         }  
  59.                     }  
  60.                 });  
  61.   
  62.         // update the ImageContainer to be the new bitmap container.  
  63.         mImageContainer = newContainer;  
  64.     }  
  65.   
  66.     ...  
  67. }  
ここで ImageLoader の get(url, imageListener) を呼んでいます。
ImageLoader には引数が4つの get(url, imageLoader, maxWidth, maxHeight) もあり、引数が2つの get() を呼んだ場合は、maxWidth, maxHeight には 0 が渡され、生成される Bitmap は実際の画像サイズになります。
  1. public class ImageLoader {  
  2.   
  3.     ...  
  4.   
  5.     public ImageContainer get(String requestUrl, final ImageListener listener) {  
  6.         return get(requestUrl, listener, 00);  
  7.     }  
  8.   
  9.     public ImageContainer get(String requestUrl, ImageListener imageListener,  
  10.             int maxWidth, int maxHeight) {  
  11.         // only fulfill requests that were initiated from the main thread.  
  12.         throwIfNotOnMainThread();  
  13.   
  14.         final String cacheKey = getCacheKey(requestUrl, maxWidth, maxHeight);  
  15.   
  16.         // Try to look up the request in the cache of remote images.  
  17.         Bitmap cachedBitmap = mCache.getBitmap(cacheKey);  
  18.         if (cachedBitmap != null) {  
  19.             // Return the cached bitmap.  
  20.             ImageContainer container = new ImageContainer(cachedBitmap, requestUrl, nullnull);  
  21.             imageListener.onResponse(container, true);  
  22.             return container;  
  23.         }  
  24.   
  25.         // The bitmap did not exist in the cache, fetch it!  
  26.         ImageContainer imageContainer =  
  27.                 new ImageContainer(null, requestUrl, cacheKey, imageListener);  
  28.   
  29.         // Update the caller to let them know that they should use the default bitmap.  
  30.         imageListener.onResponse(imageContainer, true);  
  31.   
  32.         // Check to see if a request is already in-flight.  
  33.         BatchedImageRequest request = mInFlightRequests.get(cacheKey);  
  34.         if (request != null) {  
  35.             // If it is, add this request to the list of listeners.  
  36.             request.addContainer(imageContainer);  
  37.             return imageContainer;  
  38.         }  
  39.   
  40.         // The request is not already in flight. Send the new request to the network and  
  41.         // track it.  
  42.         Request<?> newRequest =  
  43.             new ImageRequest(requestUrl, new Listener<Bitmap>() {  
  44.                 @Override  
  45.                 public void onResponse(Bitmap response) {  
  46.                     onGetImageSuccess(cacheKey, response);  
  47.                 }  
  48.             }, maxWidth, maxHeight,  
  49.             Config.RGB_565, new ErrorListener() {  
  50.                 @Override  
  51.                 public void onErrorResponse(VolleyError error) {  
  52.                     onGetImageError(cacheKey, error);  
  53.                 }  
  54.             });  
  55.   
  56.         mRequestQueue.add(newRequest);  
  57.         mInFlightRequests.put(cacheKey,  
  58.                 new BatchedImageRequest(newRequest, imageContainer));  
  59.         return imageContainer;  
  60.     }  
  61. }  
maxWidth と maxHeight は ImageRequest のコンストラクタに渡されています。
  1. public class ImageRequest extends Request<Bitmap> {  
  2.   
  3.     ...  
  4.   
  5.     private final int mMaxWidth;  
  6.     private final int mMaxHeight;  
  7.   
  8.     ...  
  9.   
  10.     public ImageRequest(String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight,  
  11.             Config decodeConfig, Response.ErrorListener errorListener) {  
  12.         super(Method.GET, url, errorListener);  
  13.         setRetryPolicy(  
  14.                 new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES, IMAGE_BACKOFF_MULT));  
  15.         mListener = listener;  
  16.         mDecodeConfig = decodeConfig;  
  17.         mMaxWidth = maxWidth;  
  18.         mMaxHeight = maxHeight;  
  19.     }  
  20.   
  21.     ...  
  22.   
  23.     /** 
  24.      * The real guts of parseNetworkResponse. Broken out for readability. 
  25.      */  
  26.     private Response<Bitmap> doParse(NetworkResponse response) {  
  27.         byte[] data = response.data;  
  28.         BitmapFactory.Options decodeOptions = new BitmapFactory.Options();  
  29.         Bitmap bitmap = null;  
  30.         if (mMaxWidth == 0 && mMaxHeight == 0) {  
  31.             decodeOptions.inPreferredConfig = mDecodeConfig;  
  32.             bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);  
  33.         } else {  
  34.             // If we have to resize this image, first get the natural bounds.  
  35.             decodeOptions.inJustDecodeBounds = true;  
  36.             BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);  
  37.             int actualWidth = decodeOptions.outWidth;  
  38.             int actualHeight = decodeOptions.outHeight;  
  39.   
  40.             // Then compute the dimensions we would ideally like to decode to.  
  41.             int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight,  
  42.                     actualWidth, actualHeight);  
  43.             int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth,  
  44.                     actualHeight, actualWidth);  
  45.   
  46.             // Decode to the nearest power of two scaling factor.  
  47.             decodeOptions.inJustDecodeBounds = false;  
  48.             // TODO(ficus): Do we need this or is it okay since API 8 doesn't support it?  
  49.             // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;  
  50.             decodeOptions.inSampleSize =  
  51.                 findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);  
  52.             Bitmap tempBitmap =  
  53.                 BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);  
  54.   
  55.             // If necessary, scale down to the maximal acceptable size.  
  56.             if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||  
  57.                     tempBitmap.getHeight() > desiredHeight)) {  
  58.                 bitmap = Bitmap.createScaledBitmap(tempBitmap,  
  59.                         desiredWidth, desiredHeight, true);  
  60.                 tempBitmap.recycle();  
  61.             } else {  
  62.                 bitmap = tempBitmap;  
  63.             }  
  64.         }  
  65.   
  66.         if (bitmap == null) {  
  67.             return Response.error(new ParseError(response));  
  68.         } else {  
  69.             return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));  
  70.         }  
  71.     }  
  72. }  
ImageRequest の doParse() で、mMaxWidth == 0 && mMaxHeight == 0 のときはバイト配列をそのまま Bitmap にしているのがわかりますね。
それ以外のときは BitmapFactory.Options の inJustDecodeBounds や inSampleSize を使って Bitmap をスケールしています。

以下では、View のサイズがわかっている場合はそのサイズを使い、わからないときは画面サイズを指定するようにしてみました。
  1. public class NetworkImageView extends ImageView {  
  2.   
  3.     ...  
  4.   
  5.     private void loadImageIfNecessary(final boolean isInLayoutPass) {  
  6.         int width = getWidth();  
  7.         int height = getHeight();  
  8.   
  9.         ...  
  10.   
  11.         DisplayMetrics metrics = getResources().getDisplayMetrics();  
  12.         int w = width > 0 ? width : metrics.widthPixels;  
  13.         int h = height > 0 ? height : metrics.heightPixels;  
  14.   
  15.         // The pre-existing content of this view didn't match the current URL. Load the new image  
  16.         // from the network.  
  17.         ImageContainer newContainer = mImageLoader.get(mUrl,  
  18.                 new ImageListener() {  
  19.                     @Override  
  20.                     public void onErrorResponse(VolleyError error) {  
  21.                         if (mErrorImageId != 0) {  
  22.                             setImageResource(mErrorImageId);  
  23.                         }  
  24.                     }  
  25.   
  26.                     @Override  
  27.                     public void onResponse(final ImageContainer response, boolean isImmediate) {  
  28.                         // If this was an immediate response that was delivered inside of a layout  
  29.                         // pass do not set the image immediately as it will trigger a requestLayout  
  30.                         // inside of a layout. Instead, defer setting the image by posting back to  
  31.                         // the main thread.  
  32.                         if (isImmediate && isInLayoutPass) {  
  33.                             post(new Runnable() {  
  34.                                 @Override  
  35.                                 public void run() {  
  36.                                     onResponse(response, false);  
  37.                                 }  
  38.                             });  
  39.                             return;  
  40.                         }  
  41.   
  42.                         if (response.getBitmap() != null) {  
  43.                             setImageBitmap(response.getBitmap());  
  44.                         } else if (mDefaultImageId != 0) {  
  45.                             setImageResource(mDefaultImageId);  
  46.                         }  
  47.                     }  
  48.                 }, w, h);  
  49.   
  50.         // update the ImageContainer to be the new bitmap container.  
  51.         mImageContainer = newContainer;  
  52.     }  
  53. }  




Volley で大きい画像を処理してはいけない

Google I/O 2013 のセッションでも言われてましたね。

ネットワークのレスポンスは com.android.volley.toolbox.BasicNetwork の performRequest() で処理されて、entity は entityToBytes() で一旦バイト配列に格納されます。

https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/BasicNetwork.java
  1. @Override  
  2. public NetworkResponse performRequest(Request<?> request) throws VolleyError {  
  3.   
  4.     ...  
  5.   
  6.             // Some responses such as 204s do not have content.  We must check.  
  7.             if (httpResponse.getEntity() != null) {  
  8.               responseContents = entityToBytes(httpResponse.getEntity());  
  9.             } else {  
  10.               // Add 0 byte response as a way of honestly representing a  
  11.               // no-content request.  
  12.               responseContents = new byte[0];  
  13.             }  
  14.     ...  
  15. }  
  16.   
  17. ...  
  18.   
  19. /** Reads the contents of HttpEntity into a byte[]. */  
  20. private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError {  
  21.     PoolingByteArrayOutputStream bytes =  
  22.             new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength());  
  23.     byte[] buffer = null;  
  24.     try {  
  25.         InputStream in = entity.getContent();  
  26.         if (in == null) {  
  27.             throw new ServerError();  
  28.         }  
  29.         buffer = mPool.getBuf(1024);  
  30.         int count;  
  31.         while ((count = in.read(buffer)) != -1) {  
  32.             bytes.write(buffer, 0, count);  
  33.         }  
  34.         return bytes.toByteArray();  
  35.     } finally {  
  36.         try {  
  37.             // Close the InputStream and release the resources by "consuming the content".  
  38.             entity.consumeContent();  
  39.         } catch (IOException e) {  
  40.             // This can happen if there was an exception above that left the entity in  
  41.             // an invalid state.  
  42.             VolleyLog.v("Error occured when calling consumingContent");  
  43.         }  
  44.         mPool.returnBuf(buffer);  
  45.         bytes.close();  
  46.     }  
  47. }  
entityToBytes() では、PoolingByteArrayOutputStream の write() を呼んでいます。 https://android.googlesource.com/platform/frameworks/volley/+/master/src/com/android/volley/toolbox/PoolingByteArrayOutputStream.java
  1. public class PoolingByteArrayOutputStream extends ByteArrayOutputStream {  
  2.   
  3.     ...  
  4.   
  5.     /** 
  6.      * Ensures there is enough space in the buffer for the given number of additional bytes. 
  7.      */  
  8.     private void expand(int i) {  
  9.         /* Can the buffer handle @i more bytes, if not expand it */  
  10.         if (count + i <= buf.length) {  
  11.             return;  
  12.         }  
  13.         byte[] newbuf = mPool.getBuf((count + i) * 2);  
  14.         System.arraycopy(buf, 0, newbuf, 0, count);  
  15.         mPool.returnBuf(buf);  
  16.         buf = newbuf;  
  17.     }  
  18.   
  19.     @Override  
  20.     public synchronized void write(byte[] buffer, int offset, int len) {  
  21.         expand(len);  
  22.         super.write(buffer, offset, len);  
  23.     }  
  24. }  
PoolingByteArrayOutputStream の write() では、バッファのサイズが足りない場合 mPool.getBuf() で現在の2倍の配列を確保しようとします。

このように、(Bitmap化する際に縮小する場合でも)いったん元サイズのまま byte 配列に確保されるため、これを並列処理で行ったりすると OutOfMemory Error になることがあります(特に古いデバイスでは)。

Honeycomb (API Level 11) で AsyncTask の実行がシングルスレッドに戻ったのって、こういうメモリエラー回避のためなのかなとか思ったり思わなかったり。ちなみに AsyncTask は API Level 3 で追加されたのですが、追加されたときはシングルスレッドでの実行でした。スレッドプールによる並列処理になったのは Donut (API Level 4) からです。

「2.x のデバイス + Volley + 大きい画像 + AsyncTask」は危険!ということですね。



2013年11月18日月曜日

Android 7 inch 用にスケールアップする場合の文字サイズ

スマホのレイアウトをそのまま 7 inch で表示すると多少スカスカになります。
レイアウトを最適化するほどではない場合、全体的なサイズを大きくして調整することがよくあります。
こういうときは、だいたい1.5倍にするといい感じになります。

文字サイズの場合は、1.5倍にすると大きすぎるので、 デフォルトの文字サイズに対応する私なりの値をメモっておきます。

res/values/dimens.xml
  1. <!--xml version="1.0" encoding="utf-8"?-->  
  2. <resources>  
  3.   
  4.     <!-- Basic -->  
  5.     <dimen name="text_size_large">22sp</dimen>  
  6.     <dimen name="text_size_medium">18sp</dimen>  
  7.     <dimen name="text_size_small">14sp</dimen>  
  8.   
  9. </resources>  


res/values-sw600dp/dimens.xml
  1. <!--xml version="1.0" encoding="utf-8"?-->  
  2. <resources>  
  3.   
  4.     <!-- Basic -->  
  5.     <dimen name="text_size_large">30sp</dimen>  
  6.     <dimen name="text_size_medium">25sp</dimen>  
  7.     <dimen name="text_size_small">20sp</dimen>  
  8.   
  9. </resources>  


res/values/styles.xml
  1. <!--xml version="1.0" encoding="utf-8"?-->  
  2. <resources>  
  3.   
  4.     <style name="AppBaseTheme" parent="Theme.Holo.Light.DarkActionBar">  
  5.         <item name="android:textAppearanceLarge">@style/TextAppearanceLarge</item>  
  6.         <item name="android:textAppearanceMedium">@style/TextAppearanceMedium</item>  
  7.         <item name="android:textAppearanceSmall">@style/TextAppearanceSmall</item>  
  8.     </style>  
  9.   
  10.     <style name="TextAppearanceLarge" parent="@android:style/TextAppearance.Large">  
  11.         <item name="android:textSize">@dimen/text_size_large</item>  
  12.     </style>  
  13.   
  14.     <style name="TextAppearanceMedium" parent="@android:style/TextAppearance.Medium">  
  15.         <item name="android:textSize">@dimen/text_size_medium</item>  
  16.     </style>  
  17.   
  18.     <style name="TextAppearanceSmall" parent="@android:style/TextAppearance.Small">  
  19.         <item name="android:textSize">@dimen/text_size_small</item>  
  20.     </style>  
  21.   
  22. </resources>  





2013年11月14日木曜日

KitKat (Android 4.4) の UI について

Android 4.4 KitKat 冬コミ原稿リレーの 11/14 分です。

Android 4.4 KitKat の API の内、User Interface に関わる部分を取り上げます。


■ Immersive full-screen mode

昔々、2.x まではフルスクリーンモードというものがありました。このときはホームキーやバックキーがハードキー(ハードボタン)だったため、ステータスバーが隠れ、画面全体がアプリの領域になるというものでした。

3.x になると、画面下部がナビゲーションバーというものになり、ステータスバーの情報はナビゲーションバーの右側に、ホームキーやバックキーは左側に移動しました。 このナビゲーションバーは、これまでのフルスクリーンモードを指定しても表示されたままでした。

4.0 ICS (API Level 14) になると、スマホにもナビゲーションバーが導入されました。
ハードキーよ、さようなら。
ナビゲーションバーを暗くしたり、インタラクションがない間(動画を見てるなど)非表示にすることができるようになりました。
  • SYSTEM_UI_FLAG_VISIBLE (0x00000000)
  • SYSTEM_UI_FLAG_LOW_PROFILE (0x00000001)
    ナビゲーションバーを暗くする(オーバーフローメニューを表示するとなぜかクリアされる。Action Item のクリックではクリアされない)
  • SYSTEM_UI_FLAG_HIDE_NAVIGATION (0x00000002)
    インタラクションがない間ナビゲーションバーを非表示にする (ちなみに、SYSTEM_UI_FLAG_LOW_PROFILE と SYSTEM_UI_FLAG_HIDE_NAVIGATION を両方指定すると、ナビゲーションバーは非表示になり、インタラクションがあって表示された瞬間は暗くなっていて、すぐに明るくなる)

4.1 Jelly Bean (API Level 16) では、ナビゲーションバーやステータスバー(これらを合わせてシステムバーとドキュメントでは書かれている)の見た目を制御するためのフラグがいくつか追加されました。
  • SYSTEM_UI_FLAG_FULLSCREEN (0x00000004)
    ステータスバーを非表示にする
    SYSTEM_UI_FLAG_LOW_PROFILE や SYSTEM_UI_FLAG_HIDE_NAVIGATION と組み合わせて指定すると、ナビゲーションバーが表示されるタイミングでステータスバーも表示される
    単体で指定した場合はインタラクションがあっても非表示のまま
  • SYSTEM_UI_FLAG_LAYOUT_STABLE (0x00000100)
  • SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION (0x00000200)
    ナビゲーションバーが非表示であるかのようにビューをレイアウトする
  • SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN (0x00000400)
    ステータスバーが非表示であるかのようにビューをレイアウトする
SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN だけを指定した状態


4.4 KitKat (API Level 19) では、インタラクションがあってもシステムバーを非表示のままにできるようになりました。
  • SYSTEM_UI_FLAG_IMMERSIVE (0x00000800)
  • SYSTEM_UI_FLAG_IMMERSIVE_STICKY (0x00001000)
* immersive は没入とか没頭という意味です。

SYSTEM_UI_FLAG_HIDE_NAVIGATION フラグや SYSTEM_UI_FLAG_FULLSCREEN フラグと組み合わせて setSystemUiVisibility() に指定します。
これらを指定すると、ステータスバー(SYSTEM_UI_FLAG_FULLSCREEN)やナビゲーションバー(SYSTEM_UI_FLAG_HIDE_NAVIGATION)が非表示になり、画面全体をアプリの領域にできます。
システムバーを表示するには、「システムバーが表示されるべき領域から内側に向かってフリック」します。
ユーザーがこの操作を行うと、SYSTEM_UI_FLAG_HIDE_NAVIGATION フラグと SYSTEM_UI_FLAG_FULLSCREEN フラグがクリアされるので、全画面表示ではなくなります。
SYSTEM_UI_FLAG_IMMERSIVE を指定した場合は、そのまま全画面表示が解除されたままになり、SYSTEM_UI_FLAG_IMMERSIVE_STICKY を指定すると数秒後に再び全画面表示に戻ります。

なぜか、オーバーフローメニューを表示すると immersive mode がクリアされてしまいます。。。


SYSTEM_UI_FLAG_IMMERSIVE | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION

わーい。全画面だー。

SYSTEM_UI_FLAG_IMMERSIVE_STICKY | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION で「システムバーが表示されるべき領域から内側に向かってフリック」したとき

View の上に半透明で表示されます

初めて全画面表示したときは、こんなポップアップが自動で出ました。




■ Translucent system bars

システムバーを透明にすることができるようになりました。

システムバーが透明のテーマが用意されています。
  • Theme.Holo.NoActionBar.TranslucentDecor
  • Theme.Holo.Light.NoActionBar.TranslucentDecor
ActionBar とは併用できないんですかね。。。

Theme.Holo.NoActionBar.TranslucentDecor

黒わからん。。。w

Theme.Holo.Light.NoActionBar.TranslucentDecor
  1. 1592     <style name="Theme.Holo.NoActionBar.TranslucentDecor">  
  2. 1593         <item name="android:windowTranslucentStatus">true</item>  
  3. 1594         <item name="android:windowTranslucentNavigation">true</item>  
  4. 1595         <item name="android:windowContentOverlay">@null</item>  
  5. 1596     </style>  
ステータスバーを透明にする属性が android:windowTranslucentStatus
ナビゲーションバーを透明にする属性が android:windowTranslucentNavigation
です。

試しに ActionBar と併用してみました。
  1. <style name="AppBaseTheme" parent="android:Theme.Holo.Light.DarkActionBar">  
  2.      <item name="android:windowTranslucentStatus">true</item>  
  3.      <item name="android:windowTranslucentNavigation">true</item>  
  4.      <item name="android:windowContentOverlay">@null</item>  
  5. </style>  
としたら、こうなりました。。。ひどいw


android:fitsSystemWindows="true" を指定すると、システムバー分のパディングがセットされます。 ただし、android:paddingXXX で指定したパディングが上書きされるので注意が必要。
  1. <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" ...="" android:fitssystemwindows="true">  
  2.   
  3.     ...  
  4.   
  5. </relativelayout>  
左右の padding もなくなってしまった。。。



■ Enhanced notification listener

API Level 18 で追加された NotificationListenerService が拡張されました。

Notification に新しく extras というフィールドが増えて、この Bundle 用のキーがいろいろ追加されました。 また、新しく actions というフィールドも増えました。このフィールドは Notification.Action の配列で、Notification.Builder の addAction() で格納されます。



■ Scenes and transitions

新しく android.transtion フレームワークが提供されるようになりました。

ユーザーインタフェースの異なる状態間のアニメーションを促進するためのものだそうです。 Scene.getSceneForLayout() を使って Scene を作ります。 レイアウトを切り替える領域の ViewGroup を第1引数に、切り替えるレイアウトを第2引数に、第3引数には Context を指定します。 あとは、TransitionManager.go() を呼べば、いい感じにアニメーションでレイアウトが切り替わります。
  1. findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {  
  2.   
  3.     @Override  
  4.     public void onClick(View v) {  
  5.         ViewGroup view = (ViewGroup) findViewById(android.R.id.content);  
  6.         Scene scene = Scene.getSceneForLayout(view, R.layout.scene2, MainActivity.this);  
  7.         TransitionManager.go(scene);  
  8.     }  
  9. });  
レイアウトを切り替える領域の ViewGroup を指定して TransitionManager.beginDelayedTransition() を呼ぶと、ViewGroup の子 View が変わったときに自動でいい感じにアニメーションしてくれます。 この方法だと Scene を作る必要はありません。

# やってみたけど、アニメーションしてくれない。。。
  1. final ViewGroup view = (ViewGroup) findViewById(android.R.id.content);  
  2. TransitionManager.beginDelayedTransition(view);  
  3.   
  4.  findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {  
  5.   
  6.      @Override  
  7.      public void onClick(View v) {  
  8.          View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.scene2, view, false);  
  9.          view.addView(inflate);  
  10.      }  
  11.  });  
特定のアニメーションを指定するには、Transition を継承したクラスのインスタンスを指定します。 指定されていないときは AutoTransition が利用されます。 Fade や ChangeBounds、Visibility などいくつかのクラスがあらかじめ用意されています。
  1. Scene scene = Scene.getSceneForLayout(view, R.layout.scene2, MainActivity.this);  
  2. TransitionManager.go(scene, new ChangeBounds());  
res/transition/ に定義した XML ファイルに対して TransitionInflater.inflateTransition() を使うことでも Transition のインスタンスを作成することができます。 XML については TransitionManager のドキュメントの説明を読むのがいいです。



# 今のところ、これだ!という使い道がわかってません。。。w



明日は @checkela さんです!

2013年11月11日月曜日

ViewPager で Volley の NetworkImageView を使うときの注意点

ViewPager の子要素は、ページが変わったときにも onLayout() が呼ばれます。

整理すると、ページが切り替わると
・新しく生成されたページ(PagerAdapter の instantiateItem() が呼ばれるところ)では onLayout(true, ...) が呼ばれる
・現在の子要素全てで onLayout(false, ...) が呼ばれる


Volley の NetworkImageView (2013年11月11日)では、
  1. @Override  
  2. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  3.     super.onLayout(changed, left, top, right, bottom);  
  4.     loadImageIfNecessary(true);  
  5. }  
のようになっています。

これだとページを切り替えるたびに画像の読み込みが実行されてしまいます。

changed が true のときだけにすれば、新しく生成されたときだけ実行されるようになります。
  1. @Override  
  2. protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  3.     super.onLayout(changed, left, top, right, bottom);  
  4.     if (changed) {  
  5.         loadImageIfNecessary(true);  
  6.     }  
  7. }  



2013年10月24日木曜日

2.x と 3.x+ の Recent Apps からの起動は Intent に付く Flag が異なる

Suica Reader で試した結果なので、launchMode の設定によって変わってくるかもしれません。
Suica Reader では launchMode に singleTask を設定しています。

■ 2.3.6 (Nexus S)
NfcAdapter.ACTION_TECH_DISCOVERED による起動
flag = 268435456 = 0x10000000
FLAG_ACTIVITY_NEW_TASK

上記のあと、Recent Apps から起動
flag = 269484032 = 0x10100000
FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY


■ 4.3 (初代 Nexus 7)
NfcAdapter.ACTION_TECH_DISCOVERED による起動
flag = 0

上記のあと、Recent Apps から起動
flag = 269500416 = 0x10104000
FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY | FLAG_ACTIVITY_TASK_ON_HOME


2.3.6 との違いは FLAG_ACTIVITY_TASK_ON_HOME です。この Flag は API Level 11 からです。

2.3.6 と 4.3 では NfcAdapter.ACTION_TECH_DISCOVERED による起動時の Flag も違っていました。

Recent から起動したときの Intent は前回起動したときの Intent になります。
つまり、カードをかざして起動したあと、Recent から起動すると、カードをかざしていないのに Intent の Action は NfcAdapter.ACTION_NDEF_DISCOVEREDNfcAdapter.ACTION_TECH_DISCOVERED などになります。
NDEF データは Intent に保持されるので、それを利用する場合は問題ないのですが、カード検出後にカードと通信して直接データを読み取る場合は困ります。
カードがかざされたことによる起動なのか、Recent からの起動なのか調べるために Flag が 0 より大きいかどうかでチェックしていたのですが、2.3.6 では NfcAdapter.ACTION_TECH_DISCOVERED による起動時の Flag が 0 ではないことがわかってしまい、ちゃんと FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY をチェックしないとダメでしたね。。。



2013年10月23日水曜日

AppCompat は Dialog をサポートしていない

AppCompat には Dialog 系のテーマがありません。

AppCompat で用意されているテーマ
  • Theme.AppCompat
  • Theme.AppCompat.Light
  • Theme.AppCompat.Light.DarkActionBar


次のように自分でダイアログのテーマを作ることはできます。
android:windowBackground に指定する画像(下記だと @drawable/dialog_full_holo_light)を platform から取ってこないといけないですが。
  1. <resources xmlns:android="http://schemas.android.com/apk/res/android">  
  2.   
  3.     <style name="AppBaseTheme" parent="Theme.AppCompat.Light"></style>  
  4.   
  5.     <style name="AppTheme" parent="AppBaseTheme">  
  6.         <item name="android:windowBackground">@drawable/bg</item>  
  7.     </style>  
  8.   
  9.     <style name="AppTheme.Dialog">  
  10.         <item name="android:windowFrame">@null</item>  
  11.         <item name="android:windowBackground">@drawable/dialog_full_holo_light</item>  
  12.         <item name="android:windowIsFloating">true</item>  
  13.         <item name="android:windowContentOverlay">@null</item>  
  14.         <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>  
  15.         <item name="android:windowActionBar">false</item>  
  16.         <item name="android:windowNoTitle">true</item>  
  17.         <item name="android:windowActionModeOverlay">true</item>  
  18.         <item name="android:windowCloseOnTouchOutside">false</item>  
  19.     </style>  
  20. </resources>  
ただし、
  1. <item name="android:windowActionBar">true</item>  
  2. <item name="android:windowNoTitle">false</item>  
とすると、IllegalStateException が発生します。
  1. java.lang.IllegalStateException: ActionBarImpl can only be used with a compatible window decor layout  
つまり、Dialog で AppCompat の ActionBar は利用できないようになっている、ということです。


なので、View で実装した DialogFragment を用意することになるのかな。
  1. public class SimpleDialogFragment extends DialogFragment {  
  2.   
  3.     public static SimpleDialogFragment getInstance(String title, String message) {  
  4.         Bundle args = new Bundle();  
  5.         args.putString("title", title);  
  6.         args.putString("message", message);  
  7.         SimpleDialogFragment f = new SimpleDialogFragment();  
  8.         f.setArguments(args);  
  9.         return f;  
  10.     }  
  11.   
  12.     @Override  
  13.     public Dialog onCreateDialog(Bundle savedInstanceState) {  
  14.         Bundle args = getArguments();  
  15.         String title = args.getString("title");  
  16.         String message = args.getString("message");  
  17.   
  18.         View view = LayoutInflater.from(getActivity())  
  19.                                   .inflate(R.layout.fragment_dialog, null);  
  20.   
  21.         TextView tv;  
  22.         // title  
  23.         tv = (TextView) view.findViewById(R.id.title);  
  24.         tv.setText(title);  
  25.         // message  
  26.         tv = (TextView) view.findViewById(R.id.message);  
  27.         tv.setText(message);  
  28.   
  29.         Dialog dialog = new Dialog(getActivity(), R.style.AppTheme_Dialog);  
  30.         dialog.setContentView(view);  
  31.   
  32.         return dialog;  
  33.     }  
  34. }  
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="wrap_content"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <TextView  
  8.         android:id="@+id/title"  
  9.         style="?attr/actionBarStyle"  
  10.         android:layout_width="match_parent"  
  11.         android:layout_height="?attr/actionBarSize"  
  12.         android:gravity="center_vertical"  
  13.         android:paddingLeft="16dp"  
  14.         android:paddingRight="16dp"  
  15.         android:textAppearance="?android:attr/textAppearanceMedium" />  
  16.   
  17.     <ScrollView  
  18.         android:layout_width="match_parent"  
  19.         android:layout_height="match_parent" >  
  20.   
  21.         <TextView  
  22.             android:id="@+id/message"  
  23.             android:layout_width="match_parent"  
  24.             android:layout_height="wrap_content"  
  25.             android:layout_margin="16dip"  
  26.             android:autoLink="web|email"  
  27.             android:linksClickable="true" />  
  28.     </ScrollView>  
  29.   
  30. </LinearLayout>  




# ちなみに ActionBar Sherlock は Dialog サポートしてます