简体   繁体   English

Recyclerview 不调用 onCreateViewHolder

[英]Recyclerview not call onCreateViewHolder

My RecyclerView does not call onCreateViewHolder , onBindViewHolder even MenuViewHolder constructor, therefore nothing appears in RecyclerView .我的RecyclerView不调用onCreateViewHolderonBindViewHolder甚至MenuViewHolder构造函数,因此RecyclerView中什么也没有出现。 I put logs for debugging, and no log is shown.我放了调试日志,没有显示日志。 What might be the problem?可能是什么问题?

My adapter:我的适配器:

public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.MenuViewHolder> {
private LayoutInflater inflater;
List<Menu> data = Collections.emptyList();

public MenuAdapter(Context context, List<Menu> data) {
    Log.i("DEBUG", "Constructor");
    inflater = LayoutInflater.from(context);
    Log.i("DEBUG MENU - CONSTRUCTOR", inflater.toString());
    this.data = data;
    for(Menu menu: this.data){
        Log.i("DEBUG MENU - CONSTRUCTOR", menu.menu);
    }
}

@Override
public MenuViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflater.inflate(R.layout.row_menu, parent, false);
    MenuViewHolder holder = new MenuViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MenuViewHolder holder, int position) {
    Log.i("DEBUG MENU", "onBindViewHolder");
    Menu current = data.get(position);
    holder.title.setText(current.menu);
}

@Override
public int getItemCount() {
    return 0;
}

class MenuViewHolder extends RecyclerView.ViewHolder {
    TextView title;
    ImageView icon;

    public MenuViewHolder(View itemView) {
        super(itemView);
        title = (TextView) itemView.findViewById(R.id.menuText);
    }
}

My custom row XML:我的自定义行 XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/menuText"
    android:text="Dummy Text"
    android:layout_gravity="center_vertical"
    android:textColor="#222"/>

and my Fragment:和我的片段:

public NavigationFragment() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
    if (savedInstanceState != null) {
        mFromSavedInstaceState = true;
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    View view = inflater.inflate(R.layout.fragment_navigation, container, false);
    RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.drawer_list);
    MenuAdapter adapter = new MenuAdapter(getActivity(), getData());
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setAdapter(adapter);
    return view;
}

另一个是确保将布局管理器设置为 RecyclerView:

recycler.setLayoutManager(new LinearLayoutManager(this));

Your getItemCount method returns 0 .您的getItemCount方法returns 0 So RecyclerView never tries to instantiate a view.所以RecyclerView从不尝试实例化视图。 Make it return something greater than 0 .让它返回greater than 0东西。

for example例如

@Override
public int getItemCount() {
    return data.size();
}

添加它对我有用后,我忘了添加以下行

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

Please set layout manager to RecyclerView like below code:请像下面的代码一样将布局管理器设置为RecyclerView

RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view_right);
//set your recycler view adapter here
NavigationAdapter adapter = new NavigationAdapter(this, FragmentDrawer.getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

I really really hope this helps someone someday.我真的希望有一天这能帮助某人。 I just spent over an hour on this one going nuts!我刚刚花了一个多小时来解决这个问题!

I had this:我有这个:

projects_recycler_view.apply {
            this.layoutManager = linearLayoutManager
            this.adapter = adapter
        }

When I should have had this:当我应该有这个的时候:

projects_recycler_view.apply {
            this.layoutManager = linearLayoutManager
            this.adapter = projectAdapter
        }

Because I foolishly called my adapter adapter , it was being shadowed by the recycler view's adapter in the apply block!因为我愚蠢地调用了我的适配器adapter ,它被应用块中的回收器视图的适配器遮住了! I renamed the adapter to projectAdapter to differentiate it and problem solved!我将适配器重命名为 projectAdapter 以区分它并解决了问题!

This does not apply for your particular case.这不适用于您的特定情况。 But this might help someone else.但这可能对其他人有所帮助。

This reason could be careless usage of the following method这个原因可能是不小心使用了以下方法

recyclerView.setHasFixedSize(true);

If not used with caution, this might cause the onBindView and onCreateViewHolder to not be called at all, with no error in the logs.如果onBindView使用,这可能会导致onBindView不调用onBindViewonCreateViewHolder ,并且日志中没有错误。

For what it's worth, I observed it when I set the recycler view adapter before the adapter was actually initialized.对于它的价值,我在适配器实际初始化之前设置回收器视图适配器时观察到它。 Solution was to make sure recyclerView.setAdapter(adapter) was called with a non-null adapter解决方案是确保使用非空适配器调用recyclerView.setAdapter(adapter)

也许它对某人有帮助,但是如果您将 RecycleView 的可见性设置为 GONE,则根本不会调用适配器方法......我花了一些时间来弄清楚。

Setting the height of the TextView in the custom.xml or RecyclerView .custom.xmlRecyclerView设置TextView的高度。 If height is wrap-content , the RecyclerView will not be visible.如果 height 是wrap-content ,则RecyclerView将不可见。

This happened when my RecyclerView was inside a ScrollView and I was using Android Support Library 23.0.这发生在我的RecyclerViewScrollView并且我使用的是 Android Support Library 23.0 时。 To fix, I updated to Android Support Library 23.2:为了修复,我更新到了 Android 支持库 23.2:

In build.gradle:在 build.gradle 中:

dependencies {
    ...
    compile 'com.android.support:appcompat-v7:23.2.+'
    compile 'com.android.support:cardview-v7:23.2.+'
}

I had the same problem, because I was using android.support.constraint.ConstraintLayout in layout resource.我遇到了同样的问题,因为我在布局资源中使用了android.support.constraint.ConstraintLayout Changing to FrameLayout helped.更改为FrameLayout帮助。

Add this to Your Adapter Class将此添加到您的适配器类

 @Override
    public int getItemCount() {
        return mDataset.size();
    } 

Other option is if you send this list objetc using get,verify if you have correct reference,for example其他选项是,如果您使用 get 发送此列表 objetc,请验证您是否有正确的参考,例如

private list<objetc> listObjetc;
//Incorrect
public void setListObjetcs(list<objetc> listObjetc){
  listObjetc = listObjetc;
}

//Correct
public void setListObjetcs(list<objetc> listObjetc){
  this.listObjetc = listObjetc;
}

I struggled with this issue for many hours.我在这个问题上挣扎了好几个小时。 I was using a fragment.我正在使用一个片段。 And the issue was not returning the view .问题不是返回view Below is my code:下面是我的代码:

ProductGridBinding binding = DataBindingUtil.inflate( inflater, R.layout.product_grid, container, false);



    mLinearLayoutManager = new LinearLayoutManager(getActivity());
    mLinearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);

    binding.rvNumbers.setHasFixedSize(true);
    binding.rvNumbers.setLayoutManager(mLinearLayoutManager);
    binding.rvNumbers.setAdapter(adapter);


    View view = binding.getRoot();


    return view;

See my answer if you are using android data binding library - Make sure you are setting layout for recyclerview and item count must be greater than 0如果您使用的是 android 数据绑定库,请参阅我的回答 - 确保您正在为 recyclerview 设置布局并且项目计数必须大于 0

 @BindingAdapter({"entries", "layout"})
    public static void setEntries(RecyclerView view, ArrayList<LoginResponse.User> listOfUsers, int layoutId) {
        if (view.getAdapter() == null) {
            view.setLayoutManager(new LinearLayoutManager(view.getContext()));
            SingleLayoutAdapter adapter = new SingleLayoutAdapter(layoutId) {
                @Override
                protected Object getObjForPosition(int position) {

                    return listOfUsers.get(position);
                }

                @Override
                public int getItemCount() {
                    return listOfUsers.size();
                }
            };
            view.setAdapter(adapter);
        }
    }

Happy coding :-)快乐编码:-)

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.如果您将 wrap_content 作为列表的高度以及项目列表的高度,则不会显示任何内容并且不会调用任何 recyclerView 函数。 Fix the height of the item or put match_parent for the list height.固定项目的高度或将 match_parent 放在列表高度。 That solved my problem.那解决了我的问题。

You forget this line in the xml app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"您在 xml app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" 中忘记了这一行

or或者

    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"

In my case I set the ID of my RecyclerView to "recyclerView".就我而言,我将 RecyclerView 的 ID 设置为“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.这个 ID 似乎已经在某处定义了,因为当我将它更改为不同的 ID 时,来自适配器的方法被正确调用。

如果使用自定义适配器,请不要忘记将 ItemCount 设置为您的集合的大小。

In my case, my list size was 0 and it was not calling the onCreateViewHolder method.就我而言,我的列表大小为 0,并且没有调用 onCreateViewHolder 方法。 I needed to display a message at center for the empty list as a placeholder so I did it like this and it worked like charm.我需要在空列表的中心显示一条消息作为占位符,所以我这样做了,而且效果很好。 Answer by @Konstantin Burov helped. @Konstantin Burov 的回答有所帮助。

  @Override
public int getItemCount() {
    if (contactList.size() == 0) {
        return 1;
    } else {
        return contactList.size();
    }
}

My encouter was the onBindViewHolder( holder , position) overrided method of the RecyclerView.adaptor not being called.我遇到的是未调用 RecyclerView.adaptor 的 onBindViewHolder( holder , position) 覆盖方法。 Method onCreateViewHolder was called, getItemCount was called.方法 onCreateViewHolder 被调用,getItemCount 被调用。 If you read the specs for Recyclerview Adapter, you will learn that if you have overrided onBindViewHolder( holder, position, List payloads) will be called in favour.如果您阅读 Recyclerview Adapter 的规范,您将了解到如果您重写了 onBindViewHolder(holder, position, List payloads) 将被优先调用。 So please be careful.所以请小心。

我的错误是在 Fragment onCreateView 中夸大了错误的视图。

go to your xml. 转到你的xml。 And change your layout to wrap content. 并更改您的布局以包装内容。 The one element is hiding the next one, so the methods are not working! 一个元素隐藏了下一个元素,因此方法不起作用!

You can add this in your XML widget RecyclerView您可以在 XML 小部件 RecyclerView 中添加它

 app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"

or manually或手动

reyclerview.setLayoutManager(new LinearLayoutManager(ActivityName.this));

Please do the following thing请做以下事情

@Override
public int getItemCount() {
    return data.size();
}

In my case after changing Activity to use ViewModel and DataBinding, I had forgotten to remove setContentView method calling from onCreate method.就我而言,在将 Activity 更改为使用 ViewModel 和 DataBinding 后,我忘记从onCreate方法中删除setContentView方法调用。 By removing it my problem solved.通过删除它,我的问题解决了。

For me, it was because the setHasStableIds(true);对我来说,这是因为 setHasStableIds(true); method was set.方法设置。 Remove that and it will work删除它,它将起作用

recyclerView.setAdapter(adapter); recyclerView.setAdapter(适配器); called The recyclerView list is populated by calling the method.通过调用方法填充 recyclerView 列表。

Make sure your XML and Koltin/Java code match.确保您的XMLKoltin/Java代码匹配。 In my case, I had a problem with the ViewHolder since I had written:就我而言,自从我写了以下内容后,我就遇到了ViewHolder问题:

var txt: AppCompatTextView = itemView.findViewById(R.id.txt)

But since my XML code is:但由于我的 XML 代码是:

<TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        .../>

I had to change the privious row into:我不得不将隐私行更改为:

var txt: TextView = itemView.findViewById(R.id.txt)

In addition, I also had to remove:此外,我还必须删除:

recyclerView.setHasFixedSize(true);

I hope this can help you :)我希望这可以帮助你:)

In my case , I was missing calling notifyDataSetChanged() after setting list in adapter.就我而言,在适配器中设置列表后,我没有调用notifyDataSetChanged()

public void setUserList(List<UserList> userList) {
      this.userList = userList;
        notifyDataSetChanged();
}

In my case I miss to set the orientation in my LinearLayout.就我而言,我错过了在我的 LinearLayout 中设置方向。

After adding orientation issue fixed.添加方向问题后修复。

 android:orientation="vertical"

我的问题是 RecyclerView 的layout_heightlayout_width设置为0dp

I had an issue because i setup the layout by myself and have put我遇到了一个问题,因为我自己设置了布局并放置了

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/band_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</androidx.recyclerview.widget.RecyclerView>

and

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/band_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:textAlignment="center">

resolved my issue解决了我的问题

Not the case in the main post, but it may come in handy for someone.主帖中的情况并非如此,但它可能对某人有用。 If you set setHasStableIds(true);如果设置setHasStableIds(true); , override getItemId(position) is the adapter. , override getItemId(position)是适配器。

In my case I was returning null from onCreateView of fragment.在我的情况下,我从片段的 onCreateView 返回 null。

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding=DataBindingUtil.inflate(inflater,R.layout.fragment_add_budget,container,false)
        setRecyclerView()
        return null// that was the culprit
    }

My answer do not applies to yours but may apply to someones else cause I had the same problem you are facing.我的答案不适用于您的答案,但可能适用于其他人,因为我遇到了与您相同的问题。

So I actually did:所以我实际上做了:

RecyclerView rv = new RecyclerView(this);

instead of代替

RecyclerView rv = findViewById(R.id.Recycler);

So make sure to take a note on that.因此,请务必记下这一点。

For those having this problem in Kotlin, use this code instead:对于在 Kotlin 中遇到此问题的用户,请改用以下代码:

recycler.layoutManager = LinearLayoutManager(context)

Note that you can use LinearLayoutManager even if your recyclerView is using constraintLayout.请注意,即使您的 recyclerView 使用的是 constraintLayout,您也可以使用 LinearLayoutManager。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Recyclerview 不调用任何适配器方法 :onCreateViewHolder,onBindViewHolder, - Recyclerview not call any Adapter method :onCreateViewHolder,onBindViewHolder, RecyclerView onCreateViewHolder未被调用 - RecyclerView onCreateViewHolder not being called RecyclerView onCreateViewHolder 方法未调用 - RecyclerView onCreateViewHolder method not calling RecyclerView 不调用 onCreateViewHolder 或 onBindView - RecyclerView not calling onCreateViewHolder or onBindView RecyclerView onCreateViewHolder位置背景颜色 - RecyclerView onCreateViewHolder position background Color 更新RecyclerView适配器项而不调用OnCreateViewHolder - Update RecyclerView adapter item without calling OnCreateViewHolder RecyclerView中没有调用适配器的onCreateViewHolder和onBindViewHolder方法? - Adapter onCreateViewHolder and onBindViewHolder methods are not getting called in RecyclerView? 回收站适配器不会调用onCreateViewHolder - Recycler adapter doesn't call onCreateViewHolder 使用DPAD快速滚动时,RecyclerView onCreateViewHolder过度调用 - RecyclerView onCreateViewHolder called excessively when scrolling fast with DPAD 尽管回收了所有视图,还是调用了Recyclerview onCreateViewHolder? - Recyclerview onCreateViewHolder being called despite all views being recycled?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM