Подтвердить что ты не робот

"LayoutManager уже привязан к ошибке RecyclerView"

Я пытаюсь иметь несколько RecyclerViews в макете, но я получаю следующую ошибку: "LayoutManager уже привязан к RecyclerView"

Код Java:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_squad, container, false);

    Activity parentActivity = getActivity();
    final ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.squad_scrollview);

    final RecyclerView gkRecyclerView = (RecyclerView) view.findViewById(R.id.gk_recycler);
    final RecyclerView coachRecyclerView = (RecyclerView) view.findViewById(R.id.coach_recycler);

    coachRecyclerView.setAdapter(new SquadRecyclerAdapter(parentActivity, getSquadDummyData(0)));
    coachRecyclerView.setLayoutManager(new MyLinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false));
    coachRecyclerView.setHasFixedSize(false);

    gkRecyclerView.setAdapter(new SquadRecyclerAdapter(parentActivity, getSquadDummyData(1)));
    gkRecyclerView.setLayoutManager(new MyLinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false));
    gkRecyclerView.setHasFixedSize(false);

    scrollView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.container));

    if (parentActivity instanceof ObservableScrollViewCallbacks) {
        scrollView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity);
    }

    return view;
}

Код макета XML:

<com.github.ksoichiro.android.observablescrollview.ObservableScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/squad_scrollview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/margin_medium"
    >

    <LinearLayout
        android:id="@+id/squad_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/seasons_scrollview"
        android:divider="@drawable/nav_bar_divider"
        android:elevation="@dimen/card_elevation"
        android:orientation="vertical"
        android:showDividers="middle">

        <LinearLayout
            android:id="@+id/coach_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/margin_small"
            android:paddingLeft="@dimen/margin_standard"
            android:paddingRight="@dimen/margin_standard"
            android:paddingTop="@dimen/margin_small">

            <TextView
                android:id="@+id/squad_coach_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Coach"
                android:textSize="@dimen/text_size_standard" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/coach_recycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="@dimen/margin_small"
                android:paddingBottom="@dimen/margin_small"
                android:scrollbars="none">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/gk_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/margin_small"
            android:paddingLeft="@dimen/margin_standard"
            android:paddingRight="@dimen/margin_standard"
            android:paddingTop="@dimen/margin_small">

            <TextView
                android:id="@+id/squad_gk_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Goalkeepers"
                android:textSize="@dimen/text_size_standard" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/gk_recycler"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="@dimen/margin_small"
                android:paddingBottom="@dimen/margin_small"
                android:scrollbars="none">

            </android.support.v7.widget.RecyclerView>

        </LinearLayout>

        <LinearLayout
            android:id="@+id/def_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/margin_small"
            android:paddingLeft="@dimen/margin_standard"
            android:paddingRight="@dimen/margin_standard"
            android:paddingTop="@dimen/margin_small">

            <TextView
                android:id="@+id/squad_def_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Defense"
                android:textSize="@dimen/text_size_standard" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/mid_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/margin_small"
            android:paddingLeft="@dimen/margin_standard"
            android:paddingRight="@dimen/margin_standard"
            android:paddingTop="@dimen/margin_small">

            <TextView
                android:id="@+id/squad_mid_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Midfielders"
                android:textSize="@dimen/text_size_standard" />

        </LinearLayout>

        <LinearLayout
            android:id="@+id/for_group"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:paddingBottom="@dimen/margin_small"
            android:paddingLeft="@dimen/margin_standard"
            android:paddingRight="@dimen/margin_standard"
            android:paddingTop="@dimen/margin_small">

            <TextView
                android:id="@+id/squad_for_header"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Forwards"
                android:textSize="@dimen/text_size_standard" />

        </LinearLayout>


    </LinearLayout>


</com.github.ksoichiro.android.observablescrollview.ObservableScrollView>

MyLinearLayoutManager - это пользовательский LinearLayoutManager, который я нашел в Интернете, чтобы решить проблему с содержимым пакета SDK LinearLayoutManager.

Есть ли способ, которым я могу иметь несколько RecyclerViews в одном макете? Кажется, что я не могу подключить более одного LayoutManagers для каждого макета.

Любая помощь будет очень приветствуется :)

4b9b3361

Ответ 1

У меня тоже была эта пробема. В моей активности используются вкладки с тремя фрагментами, когда я перехожу на третью вкладку и обратно в первую (или вторую), эта ошибка возникает.

После многого поиска я узнал, что может быть сборщиком мусора, потому что я использовал сильную ссылку.

Поскольку конструктор LinearLayoutManager использует активность как параметр (а не фрагмент), активность вкладок остается активной во время изменений вкладок.

Удалив локальное поле в mlinearLayoutManager из класса и используя слабую ссылку, я мог бы избавиться от этой проблемы:

до:

public class MyFragment1 extends Fragment
    private LinearLayoutManager linearLayoutManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        linearLayoutManager = new LinearLayoutManager(getActivity());
        (...)
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        (...)
        mRecyclerView.setLayoutManager(linearLayoutManager);
    }
}

Я изменил на:

public class MyFragment1 extends Fragment {
    // private LinearLayoutManager linearLayoutManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // linearLayoutManager = new LinearLayoutManager(getActivity());
        (...)
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        (...)
        mRecyclerView.setLayoutManager(
           new LinearLayoutManager(getActivity()));
    }
}

Ответ 2

Просто нужно создать новый экземпляр:

RecyclerView recyclerView = new RecyclerView(getContext());
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()))

Ответ 3

Я столкнулся с этой ошибкой при предоставлении LayoutManager через Dagger.
Решение состоит в том, чтобы заменить внедрение менеджера макета на менеджер менеджера макета javax.inject.Provider.

@Inject
lateinit var layoutManager: Provider<RecyclerView.LayoutManager>

...

recyclerView.setLayoutManager(layoutManager.get())

Ответ 4

У меня такая же проблема. Я работаю над этим, установив нуль в экземпляр LinearLayoutManager.

public class MyFragment extends Fragment {
protected LinearLayoutManager mLinearLayoutManager;
...

@Override
public void onDestroy() {
    super.onDestroy();
    if(mLinearLayoutManager != null) // Workaround: android.support.v7.widget.LinearLayoutManager is already attached to a RecyclerView
        mLinearLayoutManager = null;
}

Ответ 5

В моем случае я объявил LinearLayoutManager глобально и пытался присоединить один и тот же экземпляр LinearLayoutManager к нескольким RecyclerView's поэтому я получил эту ошибку.

Решение состоит в том, чтобы присоединить разные LayoutManager к каждому RecyclerView потому что один LayoutManager может быть присоединен только к одному Recyclerview.

Ответ 6

Эту ошибку я столкнулся с Daggar2 и просто удалил с помощью Provider до лайнера LinearLayoutManager;

 @Inject

 Provider <LinearLayoutManager> linearLayoutManager;

 mViewDataBinding.rvResult.setLayoutManager(linearLayoutManager.get());

Ответ 7

Я решил проблему (в случае, если кто-то сталкивается с ней снова), выполнив следующие шаги:

Чистый проект

Реконструкция проекта

Недействительный кеш

После этого я скомпилировал его снова, и он работает как шарм

PS: Я не знаю, какой из трех шагов выше сделал трюк, так как я попробовал их всех сразу перед компиляцией. Если кто-то сталкивается с этим снова и каждый раз пытается выполнить эти шаги, пожалуйста, укажите, какой шаг, в частности, является решением проблемы.