Java Recyclerview 不调用任何适配器方法 :onCreateViewHolder,onBindViewHolder,

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28115553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 05:37:57  来源:igfitidea点击:

Recyclerview not call any Adapter method :onCreateViewHolder,onBindViewHolder,

javaandroidlistadapterandroid-recyclerview

提问by SanatiSharif

my RecyclerView do not call onCreateViewHolder, onBindViewHolder, therefore, does not appear nothing in recyclerview. I put logs for debugging, and no log is shown. What can be?

我的 RecyclerView 不调用 onCreateViewHolder、onBindViewHolder,因此,在 recyclerview 中不会出现任何内容。我放了调试日志,没有显示日志。可以是什么?

My adapter:

我的适配器:

public class CommentListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final int EMPTY_VIEW = 10 ;
private ArrayList<comment> mItems;
Boolean firstTime = true;
private Typeface mTf = null;
Context mContext;
public CommentListAdapter(Context context,ArrayList<comment> items){
    Log.e("Adapter", "constructor Called");
    this.mItems = items;
    mContext = context;
}
public class EmptyViewHolder extends RecyclerView.ViewHolder {
    public EmptyViewHolder(View itemView) {
        super(itemView);
    }
}
public class ViewHolder extends RecyclerView.ViewHolder{
    TextView mAuthorName;
    TextView mMessage;
    NetworkImageView mThumbnail;
    public ViewHolder(View itemView) {
        super(itemView);
        mAuthorName = (TextView)itemView.findViewById(R.id.author_name);
        mMessage = (TextView)itemView.findViewById(R.id.message);
        mThumbnail = (NetworkImageView)itemView.findViewById(R.id.author_avatar);
    }

}

public void add(comment item, int position) {
    mItems.add(position, item);
    notifyItemInserted(position);
}

public void remove(comment item) {
    int position = mItems.indexOf(item);
    mItems.remove(position);
    notifyItemRemoved(position);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
    Log.e("Adapter", "onCreateViewHolder Called");
    View v;
    if(firstTime){
        mTf = BBcTypeFace.getTypeFace(parent.getContext().getApplicationContext(),"font/bbc.ttf");
        firstTime = false;
    }
    if( viewType == EMPTY_VIEW){
        v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.comment_empty_row,parent,false);
        EmptyViewHolder evh = new EmptyViewHolder(v);
        return evh;
    }else {
        v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.comment_row, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
    Log.e("Adapter", "onBindViewHolder Called");
    if(viewHolder instanceof ViewHolder) {
        ViewHolder holder = (ViewHolder)viewHolder;
        comment c = mItems.get(position);
        Log.e("Adapter", "Comment is\n: " + c.toString());
        final ViewHolder finalHolder = holder;
        ImageRequest request = new ImageRequest(c.author_img_link, new Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap bitmap) {
                if (bitmap != null) {
                    finalHolder.mThumbnail.setImageBitmap(bitmap);
                }
            }
        }, 0, 0, null,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        VolleyLog.e("ImageLoader", volleyError.getMessage());
                        VolleyLog.e("ImageLoader", volleyError.getStackTrace());
                    }
                });
        GetVideoInfo.getInstance(mContext.getApplicationContext()).addToRequestQueue(request);
        holder.mAuthorName.setText(c.author_name);
        holder.mMessage.setText(c.Message);
        holder.mMessage.setTypeface(mTf);
        holder.mAuthorName.setTypeface(mTf);
    }
}
@Override
public int getItemCount() {
    Log.e("Adapter", "getItemCount() Called");
    return (mItems.size() > 0 ? mItems.size() : 1);
}
@Override
public int getItemViewType(int position) {
    Log.e("Adapter", "getItemViewType() Called");
    if (mItems.size() == 0) {
        return EMPTY_VIEW;
    }
    return super.getItemViewType(position);
}}

I will use public void add(comment item, int position){...}to add item in RecyclerView.

我将用于public void add(comment item, int position){...}在 RecyclerView 中添加项目。

in Fragment :

在片段中:

private RecyclerView mRecyclerView;
private CommentListAdapter mAdapter;
private LayoutManager mLayoutManager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false);
....

    mLayoutManager = new LinearLayoutManager(getActivity());
    mAdapter = new CommentListAdapter(getActivity(),new ArrayList<comment>());
    mRecyclerView = (RecyclerView)rootView.findViewById(R.id.comment_list);
    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setLayoutManager(mLayoutManager);
    mRecyclerView.setAdapter(mAdapter);
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    makeJsonObjectRequest(mItem.url);
    return rootView;
}

XML Files :

XML文件:

<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/scrollView"
    android:background="@android:color/white"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"

    android:layout_alignParentBottom="true">

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

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

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

comment_row xml file :

comment_row xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="wrap_content"
android:gravity="right"
android:background="@android:color/darker_gray">

<LinearLayout
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
    android:gravity="right">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:id="@+id/author_name"
            android:layout_alignParentTop="true"
            android:layout_toLeftOf="@+id/author_avatar"
            android:layout_toStartOf="@+id/author_avatar"
            android:gravity="right" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/message"
            android:layout_below="@+id/author_name"
            android:layout_toLeftOf="@+id/author_avatar"
            android:layout_toStartOf="@+id/author_avatar"
            android:gravity="right" />
        </LinearLayout>

<com.android.volley.toolbox.NetworkImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/author_avatar"
    android:layout_alignParentTop="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:minHeight="150dp"
    android:minWidth="150dp" /></LinearLayout>

I will add item to RecyclerView with this code :

我将使用以下代码将项目添加到 RecyclerView:

JsonObjectRequest jsonObjReqComment = new
             JsonObjectRequest(Request.Method.GET,urlJsonObj+"#comment", null,
                     new Response.Listener<JSONObject>() {
                         @Override
                         public void onResponse(JSONObject response) {
                             try {
                                 JSONArray res = response.getJSONArray("response");
                                 //Log.e("Comment","Count:"+response.toString());
                                 //Log.e("Comment","Count:"+res.length());
                                 for (int i = 0; i < res.length(); i++) {
                                     JSONObject thread = res.getJSONObject(i);
                                     JSONObject author_json = thread.getJSONObject("author");
                                     int dislikes = thread.getInt("dislikes");
                                     int likes = thread.getInt("likes");
                                     String Message = thread.getString("message");
                                     //get Author info
                                     String author_img_link = author_json.getJSONObject("avatar").getString("permalink");
                                     String author_name = author_json.getString("name");
                                     comment c = new comment(dislikes,likes,Message,author_img_link,author_name);
                                     //Log.e("Comment",c.toString());
                                     //commentsList.add(c);
                                     mAdapter.add(c,0);
                                 }

                             } catch (JSONException e) {
                                 Log.e("OnResponse","Error JSON");
                                 e.printStackTrace();
                             } catch (Exception e){
                                 Log.e("OnResponse","Error Exception");
                                 e.printStackTrace();
                             }


                         }
                     }
                     , new Response.ErrorListener() {
                 @Override
                 public void onErrorResponse(VolleyError error) {
                     VolleyLog.d("vOLLEY", "Error: " + error.getMessage());
                     // hide the progress dialog

                 }
             }
             ){
                 @Override
                 public Map<String, String> getHeaders(){
                     Map<String, String> headers = new HashMap<String, String>();
                     headers.put("User-agent", "Comment");
                     return headers;
                 }
             };

采纳答案by sohrab Aboozarkhani Fard

As @yigit guess the combination of ScrollView, RelativeLayoutcauses this problem, Just make more room for RecyclerView.

作为@yigit猜的组合ScrollViewRelativeLayout导致此问题,只是要为更多的空间RecyclerView

回答by SanatiSharif

If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and gets equal to minimum height (as per implementation) which is apparently zero.

如果 RecyclerView 被放入 ScrollView,那么在测量步骤期间,它的高度是未指定的(因为 ScrollView 允许任何高度)并且等于最小高度(根据实现),这显然为零。

ref : android: RecyclerView inside a ScrollView

ref : android: RecyclerView 在 ScrollView

Solution : - put views in row of RecyclerViews - Calculate the size of the list items and set the height of the ListView programmatically http://vardhan-justlikethat.blogspot.com/2014/04/android-listview-inside-scrollview.html

解决方案: - 将视图放在 RecyclerViews 行中 - 计算列表项的大小并以编程方式设置 ListView 的高度 http://vardhan-justlikethat.blogspot.com/2014/04/android-listview-inside-scrollview.html

回答by AAnkit

Other than @SanatiSharif's and @sohrab's answer, you have to follow below mandatory step.

除了@SanatiSharif 和@sohrab 的回答,您必须遵循以下强制性步骤。

Make sure you call setLayoutManager, something like below.

确保你打电话setLayoutManager,像下面这样。

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

before setting adapter into recyclerView, otherwise it is not going to work. You can customize it if you need. this linkwill give you some idea of how LayoutManager works.

在将adapter设置为recyclerView之前,否则将无法正常工作。如果需要,您可以自定义它。 此链接将让您了解 LayoutManager 的工作原理。

回答by Zubair Rehman

Its late but hope it will help somone. try either of the following:

它晚了,但希望它会帮助某人。尝试以下任一方法:

first solution: make sure you haven't use this line unnecessarily

第一个解决方案:确保您没有不必要地使用这条线

recyclerView.setHasFixedSize(true);

second solution: make sure you set layout manager to recyclerView

第二种解决方案:确保将布局管理器设置为 recyclerView

recycler.setLayoutManager(new LinearLayoutManager(this));

third solution: you getItemCountreturns 0, So RecyclerViewnever tries to instantiate a view. Make it return something greater than 0

第三种解决方案:您getItemCount返回 0,因此RecyclerView永远不要尝试实例化视图。让它返回大于 0 的东西

回答by David Hackro

In my case i had this structure

就我而言,我有这个结构

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

    </RelativeLayout>
</ScrollView>

i solved the problem remove Relative

我解决了问题删除相对

<ScrollView>

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

</ScrollView>

回答by gmartinsnull

Might have been a different case but for me I just forgot to set the Layout Manager as follows:

可能是另一种情况,但对我来说,我只是忘记按如下方式设置布局管理器:

LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
recycler.setLayoutManager(layoutManager);

Hope it helps :)

希望能帮助到你 :)

回答by B.shruti

In my Case I was using Fragment-> ViewPager and Tablayout -> Inside viewpagers item I used RecyclerView.

在我的案例中,我使用的是 Fragment-> ViewPager 和 Tablayout -> Inside viewpagers 项目,我使用了 RecyclerView。

So Instead of calling ViewPagerAdapter(getChildFragmentManager()), I was calling ViewPagerAdapter(getSupportFragmentManager()) , that is why any of my recycler adapter item is not getting called.

因此 ,我没有调用 ViewPagerAdapter(getChildFragmentManager()),而是调用 ViewPagerAdapter(getSupportFragmentManager()) ,这就是为什么我的任何回收器适配器项都没有被调用的原因。

So proper way to set the ViewPagerAdapter within a fragment is

所以在片段中设置 ViewPagerAdapter 的正确方法是

ViewPagerAdapter(getChildFragmentManager())

ViewPagerAdapter(getChildFragmentManager())

回答by sealroto

Is kind of silly, but another thing that can block the calls to the methods is to declare the visibility of the view as GONE.

有点傻,但另一件可以阻止对方法调用的事情是将视图的可见性声明为 GONE。

android:visibility="gone"

recyclerView.setVisibility(View.GONE);

Any of these will block the call of the methods in RecyclerView.Adapter

其中任何一个都会阻止调用 RecyclerView.Adapter 中的方法

I hope it can help someone.

我希望它可以帮助某人。