RecyclerViewUtil.java revision 2bc2daa74eef01135f717eadfab87538a9bef29f
1/*
2 * Copyright (C) 2015 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.layoutlib.bridge.android.support;
18
19import com.android.annotations.NonNull;
20import com.android.annotations.Nullable;
21import com.android.ide.common.rendering.api.LayoutLog;
22import com.android.ide.common.rendering.api.LayoutlibCallback;
23import com.android.ide.common.rendering.api.SessionParams;
24import com.android.layoutlib.bridge.Bridge;
25import com.android.layoutlib.bridge.android.BridgeContext;
26import com.android.layoutlib.bridge.android.RenderParamsFlags;
27
28import android.content.Context;
29import android.view.View;
30
31import java.lang.reflect.Method;
32
33import static com.android.layoutlib.bridge.util.ReflectionUtils.ReflectionException;
34import static com.android.layoutlib.bridge.util.ReflectionUtils.getMethod;
35import static com.android.layoutlib.bridge.util.ReflectionUtils.invoke;
36
37/**
38 * Utility class for working with android.support.v7.widget.RecyclerView
39 */
40@SuppressWarnings("SpellCheckingInspection")  // for "recycler".
41public class RecyclerViewUtil {
42
43    private static final String RV_PKG_PREFIX = "android.support.v7.widget.";
44    public static final String CN_RECYCLER_VIEW = RV_PKG_PREFIX + "RecyclerView";
45    private static final String CN_LAYOUT_MANAGER = CN_RECYCLER_VIEW + "$LayoutManager";
46    private static final String CN_ADAPTER = CN_RECYCLER_VIEW + "$Adapter";
47
48    // LinearLayoutManager related constants.
49    private static final String CN_LINEAR_LAYOUT_MANAGER = RV_PKG_PREFIX + "LinearLayoutManager";
50    private static final Class<?>[] LLM_CONSTRUCTOR_SIGNATURE = new Class<?>[]{Context.class};
51
52    /**
53     * Tries to create an Adapter ({@code android.support.v7.widget.RecyclerView.Adapter} and a
54     * LayoutManager {@code RecyclerView.LayoutManager} and assign these to the {@code RecyclerView}
55     * that is passed.
56     * <p/>
57     * Any exceptions thrown during the process are logged in {@link Bridge#getLog()}
58     */
59    public static void setAdapter(@NonNull View recyclerView, @NonNull BridgeContext context,
60            @NonNull SessionParams params) {
61        try {
62            setLayoutManager(recyclerView, context, params.getLayoutlibCallback());
63            Object adapter = createAdapter(params);
64            setProperty(recyclerView, CN_ADAPTER, adapter, "setAdapter");
65        } catch (ReflectionException e) {
66            Bridge.getLog().error(LayoutLog.TAG_BROKEN,
67                    "Error occured while trying to setup RecyclerView.", e, null);
68        }
69    }
70
71    private static void setLayoutManager(@NonNull View recyclerView, @NonNull BridgeContext context,
72            @NonNull LayoutlibCallback callback) throws ReflectionException {
73        if (getLayoutManager(recyclerView) == null) {
74            // Only set the layout manager if not already set by the recycler view.
75            Object layoutManager = createLayoutManager(context, callback);
76            setProperty(recyclerView, CN_LAYOUT_MANAGER, layoutManager, "setLayoutManager");
77        }
78    }
79
80    /** Creates a LinearLayoutManager using the provided context. */
81    @Nullable
82    private static Object createLayoutManager(@NonNull Context context,
83            @NonNull LayoutlibCallback callback)
84            throws ReflectionException {
85        try {
86            return callback.loadView(CN_LINEAR_LAYOUT_MANAGER, LLM_CONSTRUCTOR_SIGNATURE,
87                    new Object[]{ context});
88        } catch (Exception e) {
89            throw new ReflectionException(e);
90        }
91    }
92
93    @Nullable
94    private static Object getLayoutManager(View recyclerview) throws ReflectionException {
95        Method getLayoutManager = getMethod(recyclerview.getClass(), "getLayoutManager");
96        return getLayoutManager != null ? invoke(getLayoutManager, recyclerview) : null;
97    }
98
99    @Nullable
100    private static Object createAdapter(@NonNull SessionParams params) throws ReflectionException {
101        Boolean ideSupport = params.getFlag(RenderParamsFlags.FLAG_KEY_RECYCLER_VIEW_SUPPORT);
102        if (ideSupport != Boolean.TRUE) {
103            return null;
104        }
105        try {
106            return params.getLayoutlibCallback().loadView(CN_ADAPTER, new Class[0], new Object[0]);
107        } catch (Exception e) {
108            throw new ReflectionException(e);
109        }
110    }
111
112    private static void setProperty(@NonNull View recyclerView, @NonNull String propertyClassName,
113            @Nullable Object propertyValue, @NonNull String propertySetter)
114            throws ReflectionException {
115        if (propertyValue != null) {
116            Class<?> layoutManagerClass = getClassInstance(propertyValue, propertyClassName);
117            Method setLayoutManager = getMethod(recyclerView.getClass(),
118                    propertySetter, layoutManagerClass);
119            if (setLayoutManager != null) {
120                invoke(setLayoutManager, recyclerView, propertyValue);
121            }
122        }
123    }
124
125    /**
126     * Looks through the class hierarchy of {@code object} at runtime and returns the class matching
127     * the name {@code className}.
128     * <p/>
129     * This is used when we cannot use Class.forName() since the class we want was loaded from a
130     * different ClassLoader.
131     */
132    @NonNull
133    private static Class<?> getClassInstance(@NonNull Object object, @NonNull String className) {
134        Class<?> superClass = object.getClass();
135        while (superClass != null) {
136            if (className.equals(superClass.getName())) {
137                return superClass;
138            }
139            superClass = superClass.getSuperclass();
140        }
141        throw new RuntimeException("invalid object/classname combination.");
142    }
143}
144