<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[URL Memo - Medium]]></title>
        <description><![CDATA[URLメモ（Androidアプリ）の開発記録です。 - Medium]]></description>
        <link>https://medium.com/url-memo?source=rss----d11a6d84a5bc---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>URL Memo - Medium</title>
            <link>https://medium.com/url-memo?source=rss----d11a6d84a5bc---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 15:05:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/url-memo" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[スクロール時にツールバーの表示/非表示を制御する（Android）]]></title>
            <link>https://medium.com/url-memo/customize-scrolling-behavior-of-toolbar-bc950de96450?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/bc950de96450</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Wed, 22 Jan 2020 08:26:01 GMT</pubDate>
            <atom:updated>2020-01-22T08:26:01.610Z</atom:updated>
            <content:encoded><![CDATA[<p>今回、<a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>のツールバーに次の表示制御を入れてみました。</p><ul><li>画面を上方にスクロールさせた時に、ツールバーが隠れる</li><li>画面を下方にスクロールさせた時に、ツールバーが現れる</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*45_z-Sfyta3_pWAfYRCcyQ.gif" /></figure><p>本記事では、上記ツールバーの表示制御の実装方法を紹介したいと思います。</p><p>実装方法は次の通りです。</p><ul><li>レイアウトを設定する</li><li>画面遷移時にツールバーを表示させる</li></ul><p>実装にあたっては、次のページを参考にさせて頂きました。</p><p><a href="https://techblog.yahoo.co.jp/android/androidcoordinatorlayout/">AndroidのCoordinatorLayoutを使いこなして、モダンなスクロールを実装しよう</a></p><h4>レイアウトを設定する</h4><p><a href="https://developer.android.com/reference/androidx/coordinatorlayout/widget/CoordinatorLayout.html">CoordinatorLayout</a>と<a href="https://developer.android.com/reference/com/google/android/material/appbar/AppBarLayout.html">AppBarLayout</a>を利用します。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35100b2de6a4de9fe4d840210afb86b3/href">https://medium.com/media/35100b2de6a4de9fe4d840210afb86b3/href</a></iframe><p>上記のレイアウトは、プロジェクトをBasic Activityで新規作成した時のレイアウトとほぼ同じです。<br>ポイントとなる設定はToolBarに設定している app:layout_scrollFrags属性です。app:layout_scrollFrags=scroll|enterAlways で、今回やりたかったツールバーの表示制御ができます。<br>上記のレイアウト例では、属性値にsnap を追加していますが、この設定を加えるとツールバーが部分的に表示されている段階でスクロールをやめた時、ツールバーの表示されている割合により挙動が変わります。ツールバーの表示されている割合が大きければ、自動でツールバーを完全に表示させます。そうでない場合は、ツールバーを非表示にします。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*CBd-W9b-xsxSnEcQm7ATBg.gif" /><figcaption>snapを設定した場合</figcaption></figure><p>snap設定がない場合は、ツールバーはスクロールをやめた時の表示のままとなります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*VoDZc4ZLdUb-9zaNyGg3XQ.gif" /><figcaption>snapを設定していない場合</figcaption></figure><h4>画面遷移時にツールバーを表示させる</h4><p>ツールバーが非表示になっている時にFragmentを切替えると、切替え後の画面もツールバーが非表示のままなので、画面遷移時にツールバーを表示する処理を入れます。<br><a href="https://developer.android.com/guide/navigation/?hl=ja">Navigation</a>を利用していれば、NavController#addOnDestinationChangedListenerで画面遷移時の処理が実装できます。</p><pre><strong>class </strong>MainActivity : AppCompatActivity() {<br><br>    <strong>override fun </strong>onCreate(savedInstanceState: Bundle?) {<br>        ...<br>        <em>findNavController</em>(R.id.<em>mainFragment</em>)<br>            .addOnDestinationChangedListener <strong>{ </strong>_, destination, _ <strong>-&gt;<br>                </strong><em>// ツールバーを表示させる<br>                </em>findViewById&lt;AppBarLayout&gt;(R.id.<em>appBar</em>)?.<em>apply </em><strong>{<br>                    </strong>setExpanded(<strong>true</strong>, <strong>false</strong>)<br>                <strong>}<br>  </strong>          <strong>}<br>        ...<br>     </strong>}<br>}</pre><p>今回は、スクロール時にツールバーの表示/非表示を制御する方法について紹介しました。<br><a href="https://material.io/components/app-bars-top/">top app barのマテリアルデザイン</a>も参考になりました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc950de96450" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/customize-scrolling-behavior-of-toolbar-bc950de96450">スクロール時にツールバーの表示/非表示を制御する（Android）</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerViewの各アイテムを操作する機能を追加する]]></title>
            <link>https://medium.com/url-memo/implement-recyclerview-option-menu-227e48d68f50?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/227e48d68f50</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Mon, 20 Jan 2020 08:36:01 GMT</pubDate>
            <atom:updated>2020-01-20T08:36:01.417Z</atom:updated>
            <content:encoded><![CDATA[<p>URLメモにRecyclerViewに表示された各メモを操作する機能を追加したので、その辺りの実装について紹介したいと思います。<br>内容は次の通りです。</p><ul><li>RecyclerViewのアイテムに、ダイアログを表示するためのボタンを追加する</li><li>ダイアログを<a href="https://developer.android.com/guide/topics/ui/dialogs?hl=ja#DialogFragment">DialogFragment</a>を用いて作成する</li><li><a href="https://developer.android.com/guide/navigation/">Navigation</a>を利用して、ダイアログを開く</li><li>Fragment間でViewModelを共有する</li></ul><h4>機能概要</h4><p>URLメモ一覧画面の各メモに配置されたボタンを押下すると、ダイアログを表示して、アイテムを操作（編集、共有、削除）できる機能を追加しました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi_Qy6wcDs8ivqzqMVDppA.png" /></figure><h4>RecyclerViewのアイテムにダイアログを表示するためのボタンを追加する</h4><p>ボタンのイメージは、Vector Assetからmore vertアイコンを選択して作成しておきました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AaR1TXwzbTRMXaZJas3OcQ.png" /><figcaption>Vector Asset</figcaption></figure><p>RecyclerViewのアイテムのレイアウトは、先ほど作成したアイコンをImageViewで追加しました。<br>アイコンは、アイテムの右上に表示させたかったので、 上部は左側に表示しているTextViewの最上部、右端はparentに合わせるよにConstraintsを設定しています。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9090704f7520910c53d692f3695dd012/href">https://medium.com/media/9090704f7520910c53d692f3695dd012/href</a></iframe><h4>ダイアログをDialogFragmentを用いて作成する</h4><p>先ほどレイアウトに追加したアイコンを押した時に開くダイアログを作成します。<br>ダイアログはDialogFragmentを継承し、onCreateDialogをoverrideします。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49fcef59790be63a19f20d9500121c9d/href">https://medium.com/media/49fcef59790be63a19f20d9500121c9d/href</a></iframe><p>onCreateDialogでreturnするDialogは、<a href="https://developer.android.com/reference/android/app/AlertDialog.Builder.html?hl=ja">AlertDialog.Builder</a>から生成できます。AlertDialog.Builderを利用すると、ダイアログのタイトルやメッセージ、表示する項目、ボタンなどを設定できます。<br>今回は、ダイアログに３つの操作項目（編集、共有、削除）を表示したいので、 setItems で設定しています。<br> setItems の第一引数がダイアログに表示する項目リスト、第二引数に項目が選択された時に動作するリスナーをセットします。<br>第一引数に設定したarrayリソースは、/res/values/arrays.xmlに次の値を設定しています。itemの上から順にダイアログの項目として表示されます。</p><pre>&lt;<strong>resources</strong>&gt;<br>    ...<br>    &lt;<strong>array name=&quot;itemControlDialogMenu&quot;</strong>&gt;<br>        &lt;<strong>item</strong>&gt;@string/listItemMenuEdit&lt;/<strong>item</strong>&gt;<br>        &lt;<strong>item</strong>&gt;@string/listItemMenuShare&lt;/<strong>item</strong>&gt;<br>        &lt;<strong>item</strong>&gt;@string/listItemMenuDelete&lt;/<strong>item</strong>&gt;<br>    &lt;/<strong>array</strong>&gt;<br>&lt;/<strong>resources</strong>&gt;</pre><p>第二引数（<a href="https://developer.android.com/reference/android/content/DialogInterface.OnClickListener">DialogInterface.OnClickListener</a>）は、<br>リスナーの第二引数（=menuId）によりダイアログ中のどの項目が押されたか判断できるので、menuIdに応じた処理をさせています。<br>menuIdの値は、arrays.xmlに定義したitemの順番に対応しています。例えば、一番上の項目が押された場合、menuId = 0となり、以降の項目は1ずつmenuIdが増加した値が取得できます。</p><h4>Navigationを利用して、ダイアログを開く</h4><p>DialogFragmentもFragmentと同様にNavigationを利用できます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*9GV0nllq4Iba_X6e8hxgQA.png" /><figcaption>DialogFragmentをdestinationに追加する</figcaption></figure><p>先ほど作成したダイアログを開くには、Actionを定義して、NavController#navigateを実行すれば良いです。</p><pre><em>findNavController</em>().navigate(<br>    UrlMemoListFragmentDirections<br>        .actionUrlMemoListFragmentToItemControlDialogFragment(<strong>id</strong>)<br>)</pre><p>Navigationの設定方法については、<a href="https://medium.com/url-memo/navigation-basic-108e69da07fe">こちら</a>をご参照ください。</p><h4>Fragment間でViewModelを共有する</h4><p>ダイアログからメモを削除する際に、その呼出し元画面のViewModelを利用すると楽かと思い、Fragment間でViewModelを共有する方法を調べました。<br>そして、<a href="https://developer.android.com/guide/navigation/navigation-programmatic#viewmodel_%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E3%83%87%E3%82%B9%E3%83%86%E3%82%A3%E3%83%8D%E3%83%BC%E3%82%B7%E3%83%A7%E3%83%B3%E5%90%8C%E5%A3%AB%E3%81%A7_ui_%E9%96%A2%E9%80%A3%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%85%B1%E6%9C%89%E3%81%99%E3%82%8B">ナビゲーショングラフを利用するとFragment間でViewModelを共有できるとのことでやってみました。</a><br>delegateを使う場合は、次のような実装となります。<br>R.id.url_memo_navigationは、navigationタグのid属性の値です。</p><pre>val repository = ...<br>val viewModel by navGraphViewModels(R.id.url_memo_navigation) {  <br>        UrlMemoViewModelFactory(repository)<br>    }</pre><p>delegateを使わない場合は次のようになります。</p><pre>val repository = ...<br>val viewModel = ViewModelProvider(<br>    findNavController()<br>        .getViewModelStoreOwner(R.id.url_memo_navigation)<br>    , UrlMemoViewModelFactory(repository)        ).get(UrlMemoViewModel::class.java)</pre><p>ここで、ViewModelの共有の仕組みについて説明します。<br>ViewModelはViewModelProviderを利用して取得しますが、ViewModelProviderの第一引数（=ViewModelStoreOwner）はViewModelを保持するオーナーを設定しています。<br>ViewModelProvider#getはオーナーがすでに対象のViewModelを保持していればそれを返す、なければ生成&amp;保持して返す処理をしています。なので、ViewModelStoreOwnerを同一にすることで、同じViewModelのインスタンスを扱うことができます。（ViewModelProviderについては、こちらの<a href="https://medium.com/url-memo/viewmodel-viewmodelprovider-c95a19412805">記事</a>に記載しています。）<br>ViewModelStoreOwnerはActivity、Fragment、NavBackStackEntry（NavGraphごと）に実装されています。<br>オーナーをFragmentごとに設定するとFragment間でViewModelの共有はできないので、今回の場合はActivityかNavGraphに設定すると実現できます。<br>NavGraphをオーナーに設定すると、NavGraphがバックスタックにある間はViewModelが保持されます。</p><p>今回は、DialogFragmentやViewModelを共有する方法などについて紹介しました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=227e48d68f50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/implement-recyclerview-option-menu-227e48d68f50">RecyclerViewの各アイテムを操作する機能を追加する</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LiveDataをイベントで利用する場合の注意点]]></title>
            <link>https://medium.com/url-memo/livedata-using-for-event-5b3b99208a70?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/5b3b99208a70</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Sat, 18 Jan 2020 01:31:01 GMT</pubDate>
            <atom:updated>2020-01-18T01:31:01.359Z</atom:updated>
            <content:encoded><![CDATA[<p>ViewModelとLiveData、observerを用いると次のようにイベントを処理することができます。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aea3f8b30264f06dfdf79116036a27a9/href">https://medium.com/media/aea3f8b30264f06dfdf79116036a27a9/href</a></iframe><p>しかし、この実装ではイベントが発生した時に一度だけ処理したい場合（Fragmentの切替えなど）に不都合が生じます。<br>それは例えば、クリックイベントが起きる→MyFragmentから別のFragmentに切替る→バックボタンでMyFragmentに戻るケースです。<br>この場合、MyFragmentに戻った時にobserverがアクティブ状態に切替りobserverが動き出します。そして、 isNavigate はtrueが保持されているため、再度別のFragmentに切替わる処理が動作してしまいます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*yfQNXuZg7XAGq_fXd_Losw.gif" /><figcaption>バックボタン押下時に前の画面に戻れない</figcaption></figure><p>この辺りの説明や対策については、次の記事で説明されています。<br>おすすめの対策はEventラッパーを利用する方法で、LiveDataで扱う値をEventでラップして LiveData&lt;Event&lt;T&gt;&gt;のように使います。</p><p><a href="https://medium.com/androiddevelopers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150">LiveData with SnackBar, Navigation and other events (the SingleLiveEvent case)</a></p><p>Eventラッパーの実装は上記の記事を参照して頂くとして、仕組みだけ簡単に説明します。<br>Eventラッパーは、値を取り出したことがあるか判定するためのプロパティを持っており、初めて値を取り出した時（ getContentIfNotHandled実行時）に、そのプロパティをtrueにセットします。<br>2回目以降は、そのプロパティを参照して、trueならばnullを返すといった単純な仕組みです。<br>従って、observerでは、Eventラッパーから値を取り出して、nullでなければイベント処理をする実装とするだけです。</p><pre>myViewModel.showDialog.observe(this, Observer {     <br>    // itはEvent&lt;Boolean&gt;型<br>    it.getContentIfNotHandled?.let {<br>       // Fragmentを切替える<br>       findNavController().navigate(...)<br>    }<br>}</pre><p>今回は、LiveDataをイベントで利用する場合の注意点について紹介しました。<br><a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>もEventラッパーを利用しているのですが、新しいイベントを追加した時にはまってしまったので、備忘録を残そうと思いました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b3b99208a70" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/livedata-using-for-event-5b3b99208a70">LiveDataをイベントで利用する場合の注意点</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SearchViewの検索候補に検索履歴を表示する]]></title>
            <link>https://medium.com/url-memo/searchview-history-e17975e611bf?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/e17975e611bf</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Fri, 10 Jan 2020 08:59:25 GMT</pubDate>
            <atom:updated>2020-01-10T08:59:25.398Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>では、ツールバーにSearchViewを組込んで検索できるようにしています。<br>今回は、その検索機能に検索履歴を検索候補として表示できるようにします。実装方法は、<a href="https://developer.android.com/guide/topics/search">公式サイト</a>を参考にしています。<br>公式通りに実装すると、検索候補を選択後、別のアクティビティ（検索可能アクティビティ）を開始して、検索可能アクティビティで検索処理と結果の表示をさせるように動作します。<br>しかし、URLメモはすでに検索処理を実装していたので、検索候補を選択すると、検索候補をSearchViewの検索ボックスにセットするだけの動作に変えてみました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*97EHwNvqss-BQGR3cu74oA.gif" /></figure><p>実装手順は次の通りです。</p><ol><li>SearchableInfoをSearchViewに設定する</li><li>SuggestionProviderを作成する</li><li>検索候補選択時に検索可能アクティビティを開始させない</li><li>検索候補に表示する検索履歴を保存する</li></ol><h4>SearchableInfoをSearchViewに設定する</h4><p>まず、SearchableInfoのxmlをres/xml配下に作成します。<br>SearchableInfoは、SearchViewの設定を一部行うことができるxmlファイルです。</p><pre>&lt;<strong>searchable <br>    xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:label=&quot;@string/app_name&quot;<br>    android:hint=&quot;@string/listActionBarSearchHint&quot;<br>    android:searchMode=&quot;queryRewriteFromText&quot;<br>    android:searchSuggestAuthority=<br>           &quot;&lt;<em>packageName&gt;</em>.SuggestionProvider&quot;<br>    android:searchSuggestSelection=&quot; ?&quot;</strong>&gt;<br>&lt;/<strong>searchable</strong>&gt;</pre><p>SearchableInfoのxmlの構文や属性の説明は<a href="https://developer.android.com/guide/topics/search/searchable-config">こちら</a>にありますので、詳細はそちらを参照ください。<br>ざっくりとだけ説明しますと、<br>labelは、アプリ名を指す文字列リソースを指定してください。<br>hintは、SearchViewの検索ボックスが未入力の時に表示する文字列です。任意の文字列リソースを指定してください。<br>searchSuggestAuthorityとsearchSuggestSelectionは、検索候補表示の設定に関係しています。searchSuggestAuthorityの設定値は、任意の一意の文字列で十分なのですが、SuggestionProviderの完全修飾名（= パッケージ名.クラス名）が推奨されています。SuggestionProviderは、SearchViewに検索候補を提供するクラスです。こちらについては、後述します。</p><p>次に、マニフェストに検索可能アクティビティを宣言します。<br>検索可能アクティビティは、検索時に呼び出されるアクティビティのことです。<br>今回は検索時にアクティビティを変えないので、検索可能アクティビティは、メインのアクティビティと同じにします。<br>ポイントは、intent-filterに<a href="https://developer.android.com/reference/android/content/Intent.html#ACTION_SEARCH">ACTION_SEARCH</a> を受入れる設定を追加すること、meta-dataに先ほど作成したSearchableInfoを指定することです。</p><pre>&lt;<strong>manifest<br>...</strong><br>&lt;<strong>activity<br>    android:name=&quot;.MainActivity&quot;<br>    ...</strong>&gt;<br>    &lt;<strong>intent-filter</strong>&gt;<br>        &lt;<strong>action android:name=&quot;android.intent.action.MAIN&quot; </strong>/&gt;<br>        &lt;<strong>action android:name=&quot;android.intent.action.SEARCH&quot; </strong>/&gt;    <br>        &lt;<strong>category android:name=&quot;android.intent.category.LAUNCHER&quot; </strong>/&gt;<br>    &lt;/<strong>intent-filter</strong>&gt;<br>    &lt;<strong>meta-data<br>        android:name=&quot;android.app.searchable&quot;<br>        android:resource=&quot;@xml/searchable&quot; </strong>/&gt;<br>&lt;/<strong>activity</strong>&gt;</pre><p>最後に、SearchViewにSearchableInfoを設定します。<br>URLメモはSearchViewをツールバーに組込んでいるのでonCreateOptionsMenuで次のように設定しています。</p><pre><strong>override fun </strong>onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {<br>    inflater.inflate(R.menu.<em>list_menu</em>, menu)<br>    menu?.findItem(R.id.<em>listMenuSearch</em>)?.<em>apply </em>menuItem@<strong>{<br>        </strong>(<em>actionView </em><strong>as </strong>SearchView).<em>apply </em><strong>{<br>            val </strong>searchManager = getSystemService(requireContext(),<br>                                   SearchManager::<strong>class</strong>.<em>java</em>)<br>            <strong>val </strong>info = searchManager!!.getSearchableInfo(<br>                ComponentName(<br>                    <em>context</em>,<br>                    MainActivity::<strong>class</strong>.<em>java<br>                </em>)<br>            )<br>            setSearchableInfo(info)<br>...</pre><p>SearchManager#getSearchableInfoで先ほど作成したSearchableInfoを取得しているのですが、nullが返ってくる場合は、以下を疑ってみてください。</p><ul><li>ComponentNameの第二引数のアクティビティが、マニフェストに検索可能アクティビティとして宣言したアクティビティでない。</li><li>SearchableInfoのxmlの構文間違いがある。<br>例えば、文字列リソースを属性値に指定しなければならないところに、文字列を指定している等です。</li></ul><h4>SuggestionProviderを作成する</h4><p>SuggestionProviderは、SearchViewに検索候補を提供するために利用されるクラスです。<br>次のようにSearchRecentSuggestionsProviderを継承して作成します。<br>AUTHORITYは、ここで作成したSuggestionProviderクラスの完全修飾名（=SearcableInfoのsearchSuggestAuthorityと同じ値）にして下さい。</p><pre><strong>class </strong>SuggestionProvider : SearchRecentSuggestionsProvider() {<br>    <strong>init </strong>{<br>        setupSuggestions(<strong>AUTHORITY</strong>, <strong>MODE</strong>)<br>    }<br><br>    <strong>companion object </strong>{<br>        <strong>const val AUTHORITY </strong>= <strong>&quot;<em>packageName</em>.SuggestionProvider&quot;<br>        const val MODE </strong>= <em>DATABASE_MODE_QUERIES<br>    </em>}<br>}</pre><p>次に、マニフェストにコンテンツプロバイダを宣言します。<br>authoritiesは、SuggestionProviderクラスのAUTHORITYと同じ値に設定して下さい。</p><pre>&lt;<strong>manifest ...</strong>&gt;<br>    &lt;<strong>application ...</strong>&gt;<br>        &lt;<strong>provider<br>            android:name=&quot;.SuggestionProvider&quot;<br>            android:authorities=<br>              &quot;<em>packageName</em>.SuggestionProvider&quot; </strong>/&gt;<br>...</pre><h4>検索候補選択時に検索可能アクティビティを開始させない &amp; <br>検索候補に表示する検索履歴を保存する</h4><p>onCreateOptionsMenuで次のように実装をしました。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8a1bd60459ef0313d25403da5eecf5c/href">https://medium.com/media/b8a1bd60459ef0313d25403da5eecf5c/href</a></iframe><p>SearchViewのデフォルトの動きは、検索候補選択時に検索可能アクティビティを開始します。<br>今回は、選択した検索候補をSearchViewの検索ボックスにセットしたいので、SearchView#setOnSuggestionListenerにその処理をセットします。ソースコード中のコメントにも記載していますが、trueを返すことでデフォルト動作を上書くことができます（厳密には、デフォルトの処理が実行されなくなります）。</p><p>検索候補に表示する検索履歴を保存する処理は、次の処理です。</p><pre>SearchRecentSuggestions(requireContext(),<br>    SuggestionProvider.<strong>AUTHORITY</strong>, SuggestionProvider.<strong>MODE<br></strong>).saveRecentQuery(query, <strong>null</strong>)</pre><p>SearchRecentSuggestionsのコンストラクタで指定するauthorityとmodeは、今回作成したSuggestionProviderで指定した値と同じにします。<br>SearchRecentSuggestions#saveRecentQueryの第一引数は、検索候補として保存したい文字列を指定します。<br>今回は、検索ボックスにクエリを入力した後、ソフトキーボードのEnterボタンが押下された時に検索候補を保存するようにしています。</p><p>今回は、SearchViewに検索履歴を検索候補として表示する方法について紹介しました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e17975e611bf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/searchview-history-e17975e611bf">SearchViewの検索候補に検索履歴を表示する</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AndroidX Preference Libraryを利用して設定画面を作成する]]></title>
            <link>https://medium.com/url-memo/using-androidx-preference-library-5766c036d6cd?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/5766c036d6cd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Wed, 08 Jan 2020 09:32:11 GMT</pubDate>
            <atom:updated>2020-01-08T09:32:11.482Z</atom:updated>
            <content:encoded><![CDATA[<p>Android Jetpack コンポーネントの一つである<a href="https://developer.android.com/guide/topics/ui/settings">AndroidX Preference Library</a>を利用して、設定画面を作成する方法について紹介します。<br><a href="https://medium.com/url-memo">URLメモ</a>で、設定画面からテーマ（システム設定に従う/ライト/ダーク）の変更をできるようにしたので、それを題材にして説明します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*fFOjymSVIeql9PjujWeFwA.gif" /></figure><p>ちなみに、ダークテーマへの変更については、<a href="https://medium.com/url-memo/android-dark-theme-1541e559289f">こちら</a>で紹介しています。</p><p>実装手順は以下を参考にしています。</p><p><a href="https://developer.android.com/guide/topics/ui/settings">Settings | Android Developers</a></p><h4>環境設定</h4><p>build.gradleに次の依存性を追加します。</p><pre>implementation &quot;androidx.preference:preference-ktx:1.1.0&quot;</pre><h4>リソースを作成する</h4><p>設定画面のxmlを作成します。<br>リソースの新規作成で、Resource TypeをXMLに設定することで作成できます。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZkleKz3Fbak9Eo5F3gbpnQ.png" /></figure><p>今回は、下記の設定画面のxmlを作成しました。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ebbd776cb82ddfca72d1f35116001b8/href">https://medium.com/media/9ebbd776cb82ddfca72d1f35116001b8/href</a></iframe><p>設定画面のxmlと実際表示される画面との対応をまとめると次のようになります。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*xICjKdxhgq3eYk4Mp2gFSw.png" /></figure><p>以下、設定画面のxmlについて補足説明します。<br>詳細を知りたい場合は、<a href="https://developer.android.com/guide/topics/ui/settings/components-and-attributes">こちら</a>を参照ください。</p><p><strong>PreferenceCategory</strong><br>設定のグループを視覚的に分けて表示するための属性です。今回は「テーマ設定」と表示させています。</p><p><strong>ListPreference<br></strong>設定値を選択肢の中から一つ選択させるための属性です。ラジオボタンで構成されたダイアログが表示されます。<br>ダイアログ中の選択肢はentriesで設定します。今回でいうと、「システム設定に従う/ライト/ダーク」です。<br>そして、設定値はentryValuesで設定します。こちらが、Preferenceに保存される値となります。<br>entriesとentryValuesに設定する値は、<a href="https://developer.android.com/guide/topics/resources/more-resources.html#TypedArray">arraysリソース</a>で定義します。<br>entriesとentryValuesは配列のインデックスで対応しているので、entriesとentryValuesのitem数は等しくしてください。<br>対応しているとは、今回でいうとダイアログで3番目に表示されている「ダーク」を選択すると、entryValuesの3番目のitemの値（=2）がPreferenceに保存されるということです。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c4add8d6a1754f023a7f190710e6654/href">https://medium.com/media/4c4add8d6a1754f023a7f190710e6654/href</a></iframe><p>また、ダイアログで選択したラベルを設定項目の下に表示させる場合は、useSimpleSummaryProvider=true を設定します。</p><h4>設定画面をinflateする</h4><p>PreferenceFragmentCompatを継承したFragmentを作成します。<br>そして、onCreatePreferencesをoverrideしてsetPreferencesFromResourceメソッドに、設定画面のxmlのリソースIDを渡します。<br>URLメモでは次のように実装しました。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29974323991a9f164b53e23f9362d3af/href">https://medium.com/media/29974323991a9f164b53e23f9362d3af/href</a></iframe><p>Preferenceの設定値が変更された時に、何か処理をしたい場合は、Preference#setOnPreferenceChangeListenerを利用します。<br>設定画面のxmlで定義したPreferenceは、findPreferenceメソッドで取得できます。引数には取得したいPreferenceのkey（設定画面のxmlのapp:keyの属性値）をセットして下さい。<br>URLメモでは、Preference#setOnPreferenceChangeListenerにテーマを変更する処理をセットしています。</p><h4>設定画面に遷移する</h4><p>URLメモでは、onOptionsItemSelectedをoverrideして、メニューを押下した時に設定画面に遷移するようにしました。<br><a href="https://developer.android.com/guide/navigation/">Navigation</a>を利用しているので、新しくActionも追加しています。</p><pre><strong>override fun </strong>onOptionsItemSelected(item: MenuItem): Boolean {<br><br>    <strong>when </strong>(item.<em>itemId</em>) {<br>        R.id.<em>settingsFragment </em>-&gt; {<br>          <em>findNavController</em>().navigate(<br>              UrlMemoListFragmentDirections<br>                  .actionUrlMemoListFragmentToSettingsFragment()<br>          )<br>          <strong>return true<br>        </strong>}<br>        <strong>else </strong>-&gt; <strong>return super</strong>.onOptionsItemSelected(item)<br>    }<br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*2oKrJgot4QtYXAJiZNmWLg.png" /></figure><h4>設定値を取得する</h4><p>Preferenceの設定値は、次のように取得できます。<br>SharedPreferences#getStringの第一引数がPreferenceのkeyで、第二引数がPreferenceが存在していなかった時に返す値です。</p><pre><strong>val </strong>themePreference = PreferenceManager<br>                          .getDefaultSharedPreferences(context)<br><strong>val </strong>id = themePreference<br>          .getString(<strong>&quot;theme&quot;</strong>, ThemeEnum.<strong>MODE_NIGHT_FOLLOW_SYSTEM</strong>.<strong>id</strong>)</pre><p>ちなみに、URLメモは起動時にテーマを変更させるために、設定画面で設定したPreferenceの設定値を取得して、その値に応じてテーマを変更させています。<br>ThemeEnumは、Preferenceの設定値とナイトモードを対応させるために作成しています。<br>ThemeSettingは、テーマを切替える処理をするために作成しています。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed39ee19f3273dde4c19a326faf8f3a5/href">https://medium.com/media/ed39ee19f3273dde4c19a326faf8f3a5/href</a></iframe><p>今回は、AndroidX Preference Libraryを利用して設定画面を作成する方法について紹介しました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5766c036d6cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/using-androidx-preference-library-5766c036d6cd">AndroidX Preference Libraryを利用して設定画面を作成する</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Androidでダークテーマを試す]]></title>
            <link>https://medium.com/url-memo/android-dark-theme-1541e559289f?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/1541e559289f</guid>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 08:46:01 GMT</pubDate>
            <atom:updated>2020-01-06T08:46:01.065Z</atom:updated>
            <content:encoded><![CDATA[<p>Android 10以上は、システム設定（端末のテーマ設定）で、ライトテーマ/ダークテーマの切替えが可能になっています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*sLtAF11k4s8Upwklt9oFBg.gif" /><figcaption>ダークテーマへの切替え</figcaption></figure><p>そのため、Android 10以上でダークテーマに対応するには、アプリのテーマをダークテーマに対応しているテーマに設定するだけです。<br>一方、Android 10未満やアプリでテーマ変更したい場合は、上述したアプリのテーマ設定に加えて、プログラム上にライトテーマ/ダークテーマを切替える処理を実装します。</p><h4>ダークテーマに対応しているテーマを設定する</h4><p>次のテーマを継承したテーマをアプリに設定します。</p><ul><li>Theme.AppCompat.DayNight</li><li>Theme.MaterialComponents.DayNight （<a href="https://material.io/develop/android/theming/dark">MaterialComponents のダークテーマ機能</a>）</li></ul><p>今回は、Theme.MaterialComponents.DayNightを利用してみました。<br>このテーマの利用にあたっては、<a href="https://material.io/develop/android/docs/getting-started/">こちらを参照</a>して環境の設定をして下さい（dependencyの設定やcompileSdkVersionを28以上にする等の設定です）。<br>次にアプリのテーマを設定します。<br>styles.xmlに次のスタイルを定義します。</p><pre>&lt;<strong>style name=&quot;AppTheme&quot; parent=&quot;Theme.MaterialComponents.DayNight&quot;</strong>&gt;<br>    &lt;!-- Customize your theme here. --&gt;<br>    ...<br>&lt;/<strong>style</strong>&gt;</pre><p>AndroidManifest.xmlにて、上で定義したスタイルをアプリのテーマに設定します。</p><pre><strong>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    package=&quot;...&quot;&gt;<br><br>    &lt;application<br>        ...<br>        android:theme=&quot;@style/AppTheme&quot;&gt;<br>        ...<br>    &lt;/application&gt;<br>&lt;/manifest&gt;</strong></pre><h4>ダークテーマのスタイルをカスタマイズしたい場合</h4><p>ダークテーマのスタイルをカスタマイズしたい場合は、<a href="https://developer.android.com/guide/topics/resources/providing-resources?hl=ja#AlternativeResources">代替リソースの仕組み</a>を利用します。<br>res/配下に&lt;resource_name&gt;-nightディレクトリを作成して、そのディレクトリ配下にリソースを作成すれば、ダークテーマ用のリソースになります。<br>例えば、ダークテーマ用のカラーリソースを作りたい場合は、 values-night ディレクトリを作成します。そして、その配下にcolors.xmlを作成してダークテーマ用のcolorを定義していきます。<br>リソースの新規作成からも、ダークテーマ用のリソースを作成できます。qualifiersでNight Modeを指定して作成します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OChPqCiomsDz03wVrNG_Lw.png" /><figcaption>ダークテーマ用のcolorsファイルを作成する</figcaption></figure><p>URLメモでは、次のcolorsを定義しました。そして、スタイル側でそのcolorを参照することで、ライトテーマとダークテーマでスタイルが変わるようにしました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zt3wY97cAt1AgnRyhpT9Pg.png" /></figure><p>次のように動作します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*ZHOqRhbuk6Bm5-M8p27qcw.gif" /></figure><h4>プログラムからダークテーマに変更する</h4><p>Android 10未満やアプリからテーマ変更したい場合は、プログラム上でダークテーマに切替える処理をします。<br>切替える処理は、 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) を実行するのみです。<br>次のコードは、テスト用に作成したものです。<br>メニューアイコン押下時にテーマを切替える処理をしています。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41fe1fa6a36bc0cedff15900a202f844/href">https://medium.com/media/41fe1fa6a36bc0cedff15900a202f844/href</a></iframe><p>次のように動作します。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*AElHAvQans6XKmFoSzWn_A.gif" /></figure><p>今回は、ダークテーマの対応について紹介しました。<br>今度、<a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>にしっかりしたもを組込んでみようと思います。</p><p>次の記事を参考にさせて頂きました。</p><ul><li><a href="https://developer.android.com/guide/topics/ui/look-and-feel/darktheme?hl=ja">Dark theme | Android Developers</a></li><li><a href="https://medium.com/androiddevelopers/appcompat-v23-2-daynight-d10f90c83e94">DayNight — Adding a dark theme to your app</a></li><li><a href="https://qiita.com/keidroid/items/920e655fa6823b533ba1">これからAndroidでダークモードを実装するエンジニア／デザイナ向け資料 - Qiita</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1541e559289f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/android-dark-theme-1541e559289f">Androidでダークテーマを試す</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ツールバーに組込んだSearchViewのonRestoreInstanceState()が呼ばれない!?]]></title>
            <link>https://medium.com/url-memo/searchview-restore-e0b3cf66f37a?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/e0b3cf66f37a</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 01:36:01 GMT</pubDate>
            <atom:updated>2020-01-03T01:36:01.218Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>では、下記で紹介したようにツールバーに組込んだSearchViewを用いて検索機能を実装しています。</p><p><a href="https://medium.com/url-memo/searchview-to-android-room-like-sql-486ba3917479">SearchViewからAndroid Roomで部分一致検索するまで</a></p><p>先日、このSearchViewのUI状態の復元ができているか確認したところ、できていないことが分かりました。<br>ここで、UI状態の復元とはSearchViewならば検索ボックスに入力した検索キーワードがクリアされず、前の状態を引き継いでいるということです。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vd4_HdL64ZxonvmZvPnPLA.png" /><figcaption>UI状態の復元失敗</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mzb5CPSnPANEzDBVjKd4-A.png" /><figcaption>UI状態の復元成功</figcaption></figure><p>通常、UI状態、すなわちViewの復元処理はonSaveInstanceState() メソッドで復元用のデータを保存し、onRestoreInstanceState()メソッドでUI状態を復元するようAndroid（フレームワーク）側で実装されています。<br>UI状態の復元処理の仕組みについては、下記の公式ページが参考になります。</p><ul><li><a href="https://developer.android.com/guide/components/activities/activity-lifecycle.html?hl=JA#onsaveinstancestate-%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E5%8D%98%E7%B4%94%E3%81%A7%E8%BB%BD%E9%87%8F%E3%81%AA-ui-%E7%8A%B6%E6%85%8B%E3%82%92%E4%BF%9D%E5%AD%98%E3%81%99%E3%82%8B">onSaveInstanceState() を使用して単純で軽量な UI 状態を保存する</a></li><li><a href="https://developer.android.com/guide/components/activities/activity-lifecycle.html?hl=JA#%E4%BF%9D%E5%AD%98%E6%B8%88%E3%81%BF%E3%81%AE%E3%82%A4%E3%83%B3%E3%82%B9%E3%82%BF%E3%83%B3%E3%82%B9%E7%8A%B6%E6%85%8B%E3%82%92%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%A6%E3%82%A2%E3%82%AF%E3%83%86%E3%82%A3%E3%83%93%E3%83%86%E3%82%A3%E3%81%AE-ui-%E7%8A%B6%E6%85%8B%E3%82%92%E5%BE%A9%E5%85%83%E3%81%99%E3%82%8B">保存済みのインスタンス状態を使用してアクティビティの UI 状態を復元する</a></li></ul><p>しかし、ツールバーにSearchViewを組込んだ場合、ブレークポイントを貼って確認したのですが、SearchView#onRestoreInstanceStateが呼ばれていませんでした。onCreateOptionsMenuでSearchViewの設定をする前に復元処理が終わっているように見えます。<br>ということで、今回は独自で復元処理を実装することにしました。</p><p>復元処理は、次の箇所に修正を加えます。</p><ul><li>onCreateOptionsMenuメソッド</li><li>menuのxmlファイル</li></ul><h4>onCreateOptionsMenuメソッド</h4><p>まずは、メニューが作られるonCreateOptionsMenuで次のように実装します。</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8de44c8f220edec5be1539dca20fff85/href">https://medium.com/media/8de44c8f220edec5be1539dca20fff85/href</a></iframe><p>ポイントは、上のソースコードの12~17行目（「検索キーワードを復元する」とコメントをしている辺り）です。<br>viewModel.searchQueryは前回の検索キーワードです。前回の検索キーワードは、変数名の通りViewModelに検索したタイミングで保持させています。<br>expandActionView()は、ActionView（今回の場合はSearchViewのことです。）を展開するためのメソッドです。展開されると、SearchViewの場合、検索キーワードが入力できる状態になります。<br>次のsetQueryで、SearchViewの検索ボックスに前回の検索キーワードをセットしています。SearchView.OnQueryTextListener#onQueryTextSubmitを実行する必要はないため、第二引数はfalseを指定しています。<br>expandActionView()を実行すると<a href="https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/widget/SearchView.java#1407">SearchViewは内部で検索ボックスの値を空にする</a>ので、setQueryはexpandActionView()の次に実行します。<br>最後にclearFocus()を実行して、検索ボックスからフォーカスを外しています。</p><h4>menuのxmlファイル</h4><p>修正内容は、showAsAction属性の値をalwaysに設定することです。<br>ifRoomの場合、UI状態の復元後、SearchViewを閉じるとメニューから検索アイコンが消えてしまったので、この対応をしました。</p><pre>&lt;<strong>menu xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;</strong>&gt;<br>    &lt;<strong>item<br>        android:id=&quot;@+id/listMenuSearch&quot;<br>        android:icon=&quot;@android:drawable/ic_menu_search&quot;<br>        android:title=&quot;@string/listActionBarSearch&quot;<br>        app:actionViewClass=&quot;androidx.appcompat.widget.SearchView&quot;<br>        app:showAsAction=&quot;always|collapseActionView&quot; </strong>/&gt;<br>&lt;/<strong>menu</strong>&gt;</pre><p>今回は、ツールバーに組込んだSearchViewのonRestoreInstanceState()が呼ばれないこと、独自で実装した復元処理について紹介しました。<br>わざわざ独自で復元処理を実装するのは、きれいでない気がするので、検索機能は別のIntentで実行することも検討した方がいいかもと思いました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0b3cf66f37a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/searchview-restore-e0b3cf66f37a">ツールバーに組込んだSearchViewのonRestoreInstanceState()が呼ばれない!?</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ViewModel、ViewModelProviderについて調べてみた（Android）]]></title>
            <link>https://medium.com/url-memo/viewmodel-viewmodelprovider-c95a19412805?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/c95a19412805</guid>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Fri, 27 Dec 2019 09:18:51 GMT</pubDate>
            <atom:updated>2019-12-27T09:18:51.765Z</atom:updated>
            <content:encoded><![CDATA[<p>先日、<a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>の動作確認をしていたのですが、画面回転後、メモの再検索が実行され、スクロールが戻る問題に気付きました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*gOMQUGQPcaxRMP0s3S156Q.gif" /><figcaption>修正前の動作</figcaption></figure><p>期待していた動作は、</p><ul><li>画面回転後、画面回転前のメモデータが表示されていること。</li><li>画面回転後、画面スクロールの状態を保持されていること。</li></ul><p>でした。</p><p>ViewModelを使用すると、期待する動作が実現できると想定していたのですが、何故だろうという感じでした。<br>結局、原因は<a href="https://developer.android.com/reference/android/arch/lifecycle/ViewModelProvider">ViewModelProvider</a>を利用して、画面に対応するViewModelを生成 &amp; 取得していなかったからでした。実装を間違えてました😞</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*GoFgGZYHzvygw0qBUNHQdA.gif" /><figcaption>修正後の動作</figcaption></figure><p>ViewModelProviderを利用すると期待通り動作したのですが、せっかくなので、ViewModelProviderの動作について少し調べてみたので、紹介したいと思います。</p><p>ViewModelProviderは、ライフサイクルを考慮して所望のViewModelを提供するクラスです。ViewModelProviderは次のコンストラクタを使って、たいてい生成すると思います。</p><pre>public ViewModelProvider (ViewModelStoreOwner owner, <br> ViewModelProvider.Factory factory)</pre><p>引数について説明します。</p><ul><li>ViewModelStoreOwner owner<br>ViewModelStoreを返すインタフェースです。ViewModelStoreOwnerは、FragmentやAppCompatActivityで実装されているので、通常はthisを引数として渡します。<br>ここで、ViewModelStoreはViewModelを保持するクラスです。<br>ViewModelStoreは、ViewModelStoreOwner＃getViewModelStoreの実行時に<a href="https://android.googlesource.com/platform/frameworks/support/+/8514bc0f4d930b5470435aa365719b2a6a3ad2f3/activity/src/main/java/androidx/activity/ComponentActivity.java#64">Activity</a>や<a href="https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-activity-release/fragment/fragment/src/main/java/androidx/fragment/app/FragmentManagerViewModel.java#147">Fragment</a>に対応して生成されており、既にViewModelStoreが生成されている場合は、それを返却するよう実装されています。</li><li>ViewModelProvider.Factory factory<br>引数のViewModelクラスのインスタンスを生成するための、factoryです。<br>生成するViewModelのコンストラクタに引数がなければ、<br><a href="https://developer.android.com/reference/androidx/lifecycle/ViewModelProvider.NewInstanceFactory?hl=ja">ViewModelProvider.NewInstanceFactory</a>を、ViewModelが<a href="https://developer.android.com/reference/androidx/lifecycle/AndroidViewModel.html?hl=ja">AndroidViewModel</a>を継承している場合は、<a href="https://developer.android.com/reference/androidx/lifecycle/ViewModelProvider.AndroidViewModelFactory?hl=ja">ViewModelProvider.AndroidViewModelFactory</a>が使えます。<br>また、自分で実装したViewModelProvider.Factoryを指定することもできます。手抜きの例ですが、次のように実装できます。</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da5d31fe373f1ecd3ff2cd298126680e/href">https://medium.com/media/da5d31fe373f1ecd3ff2cd298126680e/href</a></iframe><p>次にViewModelの初期化ですが、ViewModelProviderを利用して次のように行います。</p><pre>val viewModel = ViewModelProvider(<strong>this</strong>, <em>yourFactory</em>)<br>                  .get(<em>YourViewModel</em>::<strong>class</strong>.<em>java</em>)</pre><p>ViewModelProvider#getが実行されると、引数で指定されたクラスと同じ型のViewModelが、ViewModelStoreに存在するかどうかで、次の動作をします。</p><ul><li>存在する場合<br>ViewModelStoreで保持していたViewModelを返します。</li><li>存在しない場合<br>引数で指定されたViewModelのインスタンスをViewModelProviderのfactoryにより生成して、それを返します。また、ViewModelStoreに生成したViewModelを保存します。</li></ul><p>ということで、あるViewModelに対して、初めてViewModelProvider#getを実行すると、そのViewModelをViewModelStoreに保存します。<br>そして、例えば画面回転により再度、ViewModelProvider#getが実行されると、すでにViewModelStoreにあるViewModelを返します。これにより、ViewModelのデータの引継ぎが可能になっています。<br>但し、ViewModelStoreはViewModelStoreOwnerのライフサイクルに従うので、例えば、ViewModelStoreOwnerがFragmentの場合、バックボタンなどを押して、そのFragmentが破棄されればViewModelStoreもクリアされます（<a href="https://android.googlesource.com/platform/frameworks/support/+/84448d71fda0a24ba5d60fe9368ac47b97564c88/fragment/src/main/java/androidx/fragment/app/FragmentManagerImpl.java#1026">この辺りかと</a>）。他にも、自分でViewModelStore#clearを実行すれば、クリアすることはできます。</p><p>今回は、ViewModel、ViewModelProviderについて調べたことを紹介しました。調べる際、ソースコードを色々と眺めてみましたが、さわりぐらいしか理解できませんでした。<br>下記の公式のページが参考になります。</p><ul><li><a href="https://developer.android.com/topic/libraries/architecture/saving-states?hl=ja">Saving UI States | Android Developers</a></li><li><a href="https://developer.android.com/guide/topics/resources/runtime-changes">Handle configuration changes | Android Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c95a19412805" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/viewmodel-viewmodelprovider-c95a19412805">ViewModel、ViewModelProviderについて調べてみた（Android）</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RecyclerViewの選択モード時にアイテムのマージン領域をタッチすると選択モードが解除される]]></title>
            <link>https://medium.com/url-memo/recyclerview-when-touch-margin-of-item-12afa8db3e72?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/12afa8db3e72</guid>
            <category><![CDATA[日本語]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Sun, 22 Dec 2019 02:01:01 GMT</pubDate>
            <atom:updated>2019-12-22T02:01:01.188Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/url-memo/introduction-6abb365ffa50">URLメモ</a>では、下記記事で紹介したようにRecyclerView中のアイテムを削除する機能を実装しています。</p><p><a href="https://medium.com/url-memo/recyclerview-delete-in-actionmode-cb7bb98a14ff">RecyclerViewの選択したアイテムの削除機能を実装する</a></p><p>アイテムのレイアウトは、CardViewを使っており、アイテム間の境界を分かりやすくするため、マージンを設定しています。マージン領域は下図でいうとオフホワイト色の領域です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*spI_YRenB1MvyQ0YDsVzlw.png" /></figure><p>ここからが本題です。<br>RecyclerViewで選択モードに入った後、選択状態にないアイテムをタッチすると、そのアイテムは選択状態となります。<br>では、上図で示したアイテムのマージン領域をタッチするとどうなるでしょうか？</p><p>答えは、<strong>選択モードが解除される</strong>です🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*mYzMpMspwimjZR6p4saYYA.gif" /></figure><p>この動作は個人的に不自然に感じるので、マージンの設定をなくしておきました。cardUseCompatPaddingがきいているようで、アイテムの境界は分かるので、ひとまずこの対応にしておこうと思います。</p><pre>&lt;<strong>androidx.cardview.widget.CardView<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;wrap_content&quot;<br>    app:isActivated=&quot;@{tracker.isSelected(item.id)}&quot;<br>    app:cardBackgroundColor=&quot;@color/edit_list_card&quot;<br>    app:cardPreventCornerOverlap=&quot;false&quot;<br>    app:cardUseCompatPadding=&quot;true&quot;</strong>&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*DCxjXepVTb7xIzu_jGrj7A.png" /></figure><p>今回は、RecyclerViewの選択モード時にアイテムのマージン領域をタッチすると選択モードが解除される事象について紹介しました。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12afa8db3e72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/recyclerview-when-touch-margin-of-item-12afa8db3e72">RecyclerViewの選択モード時にアイテムのマージン領域をタッチすると選択モードが解除される</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SelectionTrackerのデータバインディングを試してみる]]></title>
            <link>https://medium.com/url-memo/databinding-to-selectiontracker-9ff1345d18dd?source=rss----d11a6d84a5bc---4</link>
            <guid isPermaLink="false">https://medium.com/p/9ff1345d18dd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[日本語]]></category>
            <dc:creator><![CDATA[Keisuke Kawajiri]]></dc:creator>
            <pubDate>Sat, 21 Dec 2019 01:31:01 GMT</pubDate>
            <atom:updated>2019-12-21T01:31:01.011Z</atom:updated>
            <content:encoded><![CDATA[<p>以前書いた記事「<a href="https://medium.com/url-memo/recyclerview-delete-in-actionmode-cb7bb98a14ff?">RecyclerViewの選択したアイテムの削除機能を実装する</a>」で次の記載をしていましたので、もう少し検討してみました。</p><blockquote>今回はActivateの変更は<a href="https://developer.android.com/topic/libraries/data-binding/">DataBaindingとBindingAdapter</a>を用いてみました。SelectionTracker#isSelectedでitemIdに対応した選択状態を取得できるので、それをデータバイングする変数に保持させています。（選択状態を保持するオブジェクトが複数あるのは微妙ですが。。。後日もう少し検討したいと思います。）</blockquote><p>結論としては、次の修正をしました。<br>素直に選択状態を保持するオブジェクトはSelectionTrackerのみとしました。</p><ol><li>SelectionTrackerをデータバインディングする。<br>（実際は別のインタフェースを定義して、それをバインディングした方が良いと思います。）</li><li>アイテムに選択状態を保持することはやめて、layoutファイル側でバインディングしたSelectionTrackerとアイテムのID（= key）を用いて、選択状態を判定する。</li><li>アイテムの削除は、SelectionTracker#getSelectionで取得したIDに対応するデータとする。</li></ol><p>１、２の修正は次のソースコードの通りです。<br>今回は横着をして、SelectionTrackerをそのままバインディングしていますが、View側で色々な操作（選択状態のクリアやセット）ができてしまうので注意です。別のインタフェースを定義してバインディングした方が良い場合もあると思います。<br>今回の修正で、選択状態を保持するオブジェクトを一つにしたので、選択状態をクリアする時にSelectionTrackerの選択状態をクリアするだけでよくなりスッキリしました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbPMYpjLIdcC4jQaTP2w7g.png" /><figcaption>UrlMemoRecyclerViewAdapter.kt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQOfindsLDiV_T1xWgmjkw.png" /><figcaption>url_memo_recyclerview.xml</figcaption></figure><p>３については、<br>以前は、アイテムに保持させた選択状態を参照して、アイテムを削除するか決めていました。今回、アイテムから選択状態をなくしたので、<a href="https://developer.android.com/reference/androidx/recyclerview/selection/SelectionTracker.html#getSelection()">SelectionTracker#getSelection</a>で取得したkey（= ID）に基づいてデータを削除するように修正しました。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-7YPHer-3WC8VpxMmudQeQ.png" /><figcaption>UrlMemoListFragment.kt</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y042DviA3eMqW2rQMT_4iw.png" /><figcaption>UrlMemoViewModel.kt</figcaption></figure><p>今回の修正で前よりスッキリした気はしますが、依然として引っかかっている感があります。頭の片隅に置いておきます。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ff1345d18dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/url-memo/databinding-to-selectiontracker-9ff1345d18dd">SelectionTrackerのデータバインディングを試してみる</a> was originally published in <a href="https://medium.com/url-memo">URL Memo</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>