ClassPresenterSelector.java revision 0246318f27a905a31df5a8af445cfe67d31dfb68
1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
12 * the License.
13 */
14package android.support.v17.leanback.widget;
15
16import java.util.ArrayList;
17import java.util.HashMap;
18
19/**
20 * A ClassPresenterSelector selects a {@link Presenter} based on the item's
21 * Java class.
22 */
23public final class ClassPresenterSelector extends PresenterSelector {
24
25    private final ArrayList<Presenter> mPresenters = new ArrayList<Presenter>();
26
27    private final HashMap<Class<?>, Presenter> mClassMap = new HashMap<Class<?>, Presenter>();
28
29    /**
30     * Adds a presenter to be used for the given class.
31     */
32    public void addClassPresenter(Class<?> cls, Presenter presenter) {
33        mClassMap.put(cls, presenter);
34        if (!mPresenters.contains(presenter)) {
35            mPresenters.add(presenter);
36        }
37    }
38
39    @Override
40    public Presenter getPresenter(Object item) {
41        Class<?> cls = item.getClass();
42        Presenter presenter = null;
43
44        do {
45            presenter = mClassMap.get(cls);
46            cls = cls.getSuperclass();
47        } while (presenter == null && cls != null);
48
49        return presenter;
50    }
51
52    @Override
53    public Presenter[] getPresenters() {
54        return mPresenters.toArray(new Presenter[mPresenters.size()]);
55    }
56}
57