自定义视图中的动态findViewById

时间:2017-12-14 03:34:38

标签: android android-view

我正在开发一个名为Waterfall Toolbar的库。它是一个监听用户通过java提供的RecyclerView的视图,但我希望增加通过XML引用的可能性。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.hugocastelani.waterfalltoolbar.sample.SampleActivity"
    android:orientation="vertical">

    <com.hugocastelani.waterfalltoolbar.library.WaterfallToolbar
        android:id="@+id/waterfall_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:recycler_view="@id/recycler_view">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?actionBarSize"/>

    </com.hugocastelani.waterfalltoolbar.library.WaterfallToolbar>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

我可以在自定义视图类中获取RecyclerView的ID,但由于我无法使用findViewById在没有父级布局的情况下找到它,我不得不夸大父母,但我也不能,因为我的布局ID是未知的,因为每个用户都会给出他想要的名字。

简而言之,我需要一种在自定义视图中查找ViewById的方法,而不会让父项膨胀。我知道这可能是因为某些Android的布局,例如RelativeLayout,一直这样做。有谁知道怎么做?

编辑: 让我实现我的想法。下面的代码是我必须要做的目标RecyclerView

public class WaterfallToolbar extends CardView {
    ...        

    private void init() {
        final Integer recyclerViewID = typedArray.getResourceId(R.styleable.WaterfallToolbar_recycler_view, 0);
        // findViewById(recyclerViewID) returns null, so I gotta use the code below
        // parent_layout holds both custom view and recyclerview 
        View view = inflate(getContext(), R.layout.parent_layout, this);
        RecyclerView recyclerView = view.findViewById(recyclerView);
    }

    ...
}

但正如我所说,parent_layout未知。

0 个答案:

没有答案
相关问题