1/*
2 * Copyright (C) 2010 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
17package com.android.quicksearchbox.ui;
18
19import com.android.quicksearchbox.Suggestion;
20import com.android.quicksearchbox.SuggestionCursor;
21
22import android.content.Context;
23import android.view.LayoutInflater;
24import android.view.View;
25import android.view.ViewGroup;
26
27import java.util.Collection;
28import java.util.Collections;
29
30/**
31 * Suggestion view factory that inflates views from XML.
32 */
33public class SuggestionViewInflater implements SuggestionViewFactory {
34
35    private final String mViewType;
36    private final Class<?> mViewClass;
37    private final int mLayoutId;
38    private final Context mContext;
39
40    /**
41     * @param viewType The unique type of views inflated by this factory
42     * @param viewClass The expected type of view classes.
43     * @param layoutId resource ID of layout to use.
44     * @param context Context to use for inflating the views.
45     */
46    public SuggestionViewInflater(String viewType, Class<? extends SuggestionView> viewClass,
47            int layoutId, Context context) {
48        mViewType = viewType;
49        mViewClass = viewClass;
50        mLayoutId = layoutId;
51        mContext = context;
52    }
53
54    protected LayoutInflater getInflater() {
55        return (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
56    }
57
58    public Collection<String> getSuggestionViewTypes() {
59        return Collections.singletonList(mViewType);
60    }
61
62    public View getView(SuggestionCursor suggestion, String userQuery,
63            View convertView, ViewGroup parent) {
64        if (convertView == null || !convertView.getClass().equals(mViewClass)) {
65            int layoutId = mLayoutId;
66            convertView = getInflater().inflate(layoutId, parent, false);
67        }
68        if (!(convertView instanceof SuggestionView)) {
69            throw new IllegalArgumentException("Not a SuggestionView: " + convertView);
70        }
71        ((SuggestionView) convertView).bindAsSuggestion(suggestion, userQuery);
72        return convertView;
73    }
74
75    public String getViewType(Suggestion suggestion) {
76        return mViewType;
77    }
78
79    public boolean canCreateView(Suggestion suggestion) {
80        return true;
81    }
82
83}
84