program tip

RecyclerView가 onCreateViewHolder 또는 onBindView를 호출하지 않습니다.

radiobox 2021. 1. 5. 07:54
반응형

RecyclerView가 onCreateViewHolder 또는 onBindView를 호출하지 않습니다.


오류가 발생하지 않고 모든 데이터가 유효한 것 같습니다. 어떤 이유로 네더 뷰 관련 메서드가 호출되고 있습니다. 다음 사항을 확인했습니다.

  • getItemCount ()는 호출되는 유일한 어댑터 메소드이며 양의 정수 값을 반환합니다. (이것이 여러분이 보게 될 영역이라는 것을 알고 있습니다)

    • 생성자가 호출되고 멤버 변수가 유효합니다.

    • 부모보기는 수직 LinearLayout입니다. 스크롤 뷰가 없거나 자체 스크롤 속성이 보이는 다른 뷰가 없습니다.

    • 포함 된 조각보기가 생성되어 화면에 표시됩니다.

다음은 조각의 선언과 어댑터입니다. 이것이 완전히 당황했기 때문에 어떤 도움을 주시면 감사하겠습니다.

SubMenuAdapter adapter = new SubMenuAdapter(getActivity(), mContentItems);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(adapter);
public class SubMenuAdapter extends RecyclerView.Adapter<SubMenuAdapter.ViewHolder> {
private static final String TAG = String.format("==> %S", SubMenuAdapter.class.getSimpleName());

private final List<ContentItem> mContentItems;
private Context mContext;

public SubMenuAdapter(Context context, List<ContentItem> contenItems) {
    Log.d(TAG, "Constructor called");
    mContentItems = contenItems;
    mContext = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Log.d(TAG, "onCreateViewHolder called");
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_resource_efficiency, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    Log.d(TAG, "onBindViewHolder called");

    ContentItem item = mContentItems.get(position);
    holder.textName.setText(item.getName());
    FontSetter.setMyriadProRegular(mContext, holder.textName);
    Picasso.with(mContext).load("file://" + item.getPreviewImageDefault()).into(holder.imageIcon);
}

@Override
public int getItemCount() {
    Log.d(mContext, String.format("getItemCount: %d", mContentItems.size()));
    return mContentItems.size();
}

// ViewHolder
public static class ViewHolder extends RecyclerView.ViewHolder {

    TextView textName;
    ImageView imageIcon;

    public ViewHolder(View view) {
        super(view);
        textName = (TextView) view.findViewById(R.id.tv_resource_efficiency_option);
        imageIcon = (ImageView) view.findViewById(R.id.iv_resource_efficiency_icon);
    }
}

이것은 또한 누군가를 도울 수 있습니다

처음 사용

recyclerView.setAdapter(adapter);

그리고:

recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

따라서 다음과 같이 보일 것입니다.

recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

순서가 반대입니다.


한 시간 넘게 대답을 쫓고있었습니다.

어댑터를 설정하기 전에이 라이너를 호출하는 것을 잊지 마십시오.

recyclerView.setLayoutManager(new LinearLayoutManager(this));

리사이클 러 뷰에는 기본 레이아웃 관리자 옵션이 내장되어 있지 않으므로 프로그래밍 방식으로 추가해야합니다.

도움이된다면 건배합니다.


재활용 뷰가 nestedscrollview의 자식이 아닌지 확인하십시오.

예를 들어,이 코드는 작동하지 않습니다.

<android.support.v4.widget.NestedScrollView
    android:id="@+id/responder_scroll"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/darkGray"
    android:clipToPadding="false"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="24dp"
            app:cardElevation="@dimen/spacing_medium"
            app:cardUseCompatPadding="true">

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/responder_testimonial"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentTop="true"
                    android:text="Testimonial"
                    android:textSize="@dimen/general_font_size" />

                <TextView
                    android:id="@+id/responder_counter_testimonial"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_toRightOf="@+id/responder_testimonial"
                    android:text="170"
                    android:textSize="@dimen/general_font_size_small" />

                <Button
                    android:id="@+id/responder_btn_testimonial"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_alignParentTop="true"
                    android:text="Go" />

               <view
                    android:id="@+id/responder_list_testimonial"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_below="@+id/responder_testimonial"
                    class="android.support.v7.widget.RecyclerView"/>
            </RelativeLayout>
        </android.support.v7.widget.CardView>

    </FrameLayout>
</android.support.v4.widget.NestedScrollView>

그런 다음 사용합니다.

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">

<view
    android:id="@+id/responder_list_testimonial"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/responder_testimonial"
    class="android.support.v7.widget.RecyclerView"/>


이것이 누구에게도 도움이 될지 모르겠지만 거의 똑같은 문제가 발생했습니다. 내 문제는 조각 / 클래스 나 리사이클 러 어댑터에 없었습니다. 문제는 액션 바 걸린 부모 XML 레이아웃에 있었다 match_parent를 Where FrameLayout조각이 다 교체입니다 -in가 가능한 장소 표시 할 수 없습니다. 이것이 메서드가 호출되지 않은 이유입니다.

I guess similar scenarios might be the case for those facing the same problem. Double check every width and height in every XML file might be in the same tree, as the problem doesn't seem to be in the adapter at all.


My two pennies here. Just spent more than three hours debugging this.

Make sure that you have not used the following line carelessly.

recyclerView.setHasFixedSize(true);

Set the fixed size only when you are sure that the view would have a constant size. In case it is not, the onCreateViewHolder and onBindView methods might not get called at all.


I had also face the same issue where onCreateViewHolder or onBindView method was not getting invoke, only getItemCount was getting invoked. So it was basically issue with the height and weight of RecyclerView which was set to wrap_content or 0dp. After changing it to some value fixed the problem.


This is really old already, but in my case, I was using a ConstraintLayout and the height was set wrong so my view would have 0dp and then the adapter would be saving to do its job, as the view is 0dp.

Make sure height and width is ok and RecyclerView is has a positive size.


If you put wrap_content as height of your list as well as the height of your item list, nothing will show up and none of your recyclerView functions will be called.


I know this topic is old, but if you did the same learner mistake, as I did, you might find this helpful.

As I was studying on some website about RecyclerView and copying some code and adapting to my context, I have created different variables (eg users and data) which were meant to do the same thing, except some methods were calling data and some were calling users. This is an easy mistake to do as you try to understand other's code and java functionality (it happens to me all the time).

It's good to know that you can println in your console anywhere in your java code, so you can debug like that pretty easily.

Good luck!


In my case it was using setHasStableIds(true); in the adapter while some list items were returning -1 in getItemID(), so I suppose the RecyclerView was thinking they are equal.


When implementing FirebaseListAdapter , one need to take care of following points to set it up correctly.

  1. Check if recyclerview in xml has all attributes correct. Don't use wrap content for height & width, for instance.
  2. Please check if layoutManager is set & setHasFixedSize() is taken care of.
  3. Make POJO class variables so that they match firebase child attributes.
  4. FirebaseRecyclerOptions is set up.
  5. FirebaseRecyclerAdapter's onCreateViewHolder() & onBindViewHolder are there.
  6. Lifecycle events are taken care of.

Note- Using wrap_content as height of recyclerview is one of easiest mistake anyone can do. So do check that first.


Be careful about the thread you are working with adapter.
In my case the problem was calling notifyDataSetChanged() from an activity when my data came from a service. Actually the method was calling from background thread. But the app didn't crash and there was nothing in Logcat (!).
So i was called notifyDataSetChanged() in UI thread and the problem solved.

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        adapter.notifyDataSetChanged();
    }
});

I had this same issue where neither onCreateViewHolder or onBindViewHolder were being called. Changing your onCreateViewHolder method to use the Context you saved a reference to in the constructor instead of doing parent.getContext() should fix it:

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    Log.d(TAG, "onCreateViewHolder called");
    View view = LayoutInflater.from(mContext).inflate(R.layout.row_resource_efficiency, parent, false);
    return new ViewHolder(view);

In my case I set the ID of my RecyclerView to "recyclerView". It seems that this ID was already defined somewhere, because when I changed that to different ID, the methods from the adapter were called properly.

Link to the answer


I recently encountered this problem and apparently there are many possible causes. Try one or combination of these options, see which one(s) work(s) for you :)

1. Layout manager
Ensure that you set a layout manager to your recycler view as below

// create a layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(my_context);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

// get recycler view
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_id);
// set
recyclerView.setLayoutManager(linearLayoutManager);

2. Fixed Size
Ensure that you state whether your recycler view has a fixed size or not

// set fixed size
recyclerView.setHasFixedSize(true); // or false depending on implementation

3. XML
Ensure that your recycler is not nested in too many layouts which may cause confusion such as combination of ScrollView and RelativeLayout. Make it simple, see if it fixes your issue

<?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"
android:orientation="vertical">

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

In my case a had a Fragment with RecyclerView inside a ViewPager. The issue appeared because i used Fragment.getFragmentManager() instead of Fragment.getChildFragmentManager for my FragmentStatePagerAdapter's constructor.

P.S. Using Layout Inspector might be a great help at debugging this sort of issue.


In my case after changing Activity to ViewModel and using Binding, I had forgotten to remove setContentView from onCreate method. By removing it my problem solved.


if you are using constraint layout when you are set recyclerview height to match parent (0) this problem occur

ReferenceURL : https://stackoverflow.com/questions/28992929/recyclerview-not-calling-oncreateviewholder-or-onbindview

반응형