1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.quicksearchbox.ui
18 
19 import android.content.Context
20 import android.view.LayoutInflater
21 import android.view.View
22 import android.view.ViewGroup
23 import com.android.quicksearchbox.Suggestion
24 import com.android.quicksearchbox.SuggestionCursor
25 
26 /** Suggestion view factory that inflates views from XML. */
27 open class SuggestionViewInflater(
28   private val mViewType: String,
29   viewClass: Class<out SuggestionView?>,
30   layoutId: Int,
31   context: Context?
32 ) : SuggestionViewFactory {
33   private val mViewClass: Class<*>
34   private val mLayoutId: Int
35   private val mContext: Context?
36 
37   protected val inflater: LayoutInflater
38     get() = mContext?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
39 
40   override val suggestionViewTypes: Collection<String>
41     get() = listOf(mViewType)
42 
getViewnull43   override fun getView(
44     suggestion: SuggestionCursor?,
45     userQuery: String?,
46     convertView: View?,
47     parent: ViewGroup?
48   ): View? {
49     var mConvertView: View? = convertView
50     if (mConvertView == null || !mConvertView::class.equals(mViewClass)) {
51       val layoutId = mLayoutId
52       mConvertView = inflater.inflate(layoutId, parent, false)
53     }
54     if (mConvertView !is SuggestionView) {
55       throw IllegalArgumentException("Not a SuggestionView: $mConvertView")
56     }
57     (mConvertView as SuggestionView).bindAsSuggestion(suggestion, userQuery)
58     return mConvertView
59   }
60 
getViewTypenull61   override fun getViewType(suggestion: Suggestion?): String {
62     return mViewType
63   }
64 
canCreateViewnull65   override fun canCreateView(suggestion: Suggestion?): Boolean {
66     return true
67   }
68 
69   /**
70    * @param viewType The unique type of views inflated by this factory
71    * @param viewClass The expected type of view classes.
72    * @param layoutId resource ID of layout to use.
73    * @param context Context to use for inflating the views.
74    */
75   init {
76     mViewClass = viewClass
77     mLayoutId = layoutId
78     mContext = context
79   }
80 }
81