RecyclerView.Adapter onBind方法无法识别来自android

时间:2018-05-02 02:40:12

标签: android user-interface android-recyclerview recycler-adapter recyclerview-layout

创建一个包含MAX 4项目列表的简单程序,我选择 RecyclerView 而不是 ListView 进行优化。我添加了 RecyclerView 并将其绑定到我的 main.xml MainActivity ,创建了 row.xml ,定义 RecyclerView 中每个的外观和创建方式,并绑定扩展 RecyclerView.Adapter的自定义适配器 使用所需方法。我的代码发布在 - >

下面
<!-- This is row.xml -->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:id="@+id/container_4_row"
android:layout_height="@dimen/media_item_height">

<ImageView
    android:id="@+id/cover_art"
    android:layout_width="80dp"
    android:layout_height="match_parent"
    android:layout_marginEnd="50dp"
    android:background="@color/colorPrimary"
    android:contentDescription="@string/play_item"
    android:src="@drawable/ic_action_name" />

<LinearLayout
    android:id="@+id/text_container"
    android:layout_width="200dp"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/title"
        tools:text="The Best Music EVAH1111 FOREVER YOUNG I'M SOME!!!11^H^H"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="?android:attr/textColorPrimary"/>

    <TextView
        android:id="@+id/author"
        tools:text="John Doe, his brothers, his sisters, his pets and his more than amazing band"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:ellipsize="end"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="?android:attr/textColorSecondary"/>

</LinearLayout>

  

这是适配器类

public class MyRecycleAdapter extends 
RecyclerView.Adapter<MyRecycleAdapter.ViewHolder> {

// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {

    private final TextView  mAuthor, mTitle;
    private final ImageView aCover;
    private final LinearLayout textContainer;

    public ViewHolder(View v) {
        super(v);

        // Define click listener for the ViewHolder's View.
        v.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d(TAG, "onClick: Element " + getAdapterPosition() + " clicked.");
            }
        });
        this.textContainer = v.findViewById(R.id.text_container);
        this.mAuthor = v.findViewById(R.id.author);
        this.mTitle = v.findViewById(R.id.title);
        this.aCover = v.findViewById(R.id.cover_art);
    }
    private TextView getTitle() {
        return mTitle;
    }
    private TextView getAuthor() {
        return mAuthor;
    }
    private ImageView getaCover() {
        return aCover;
    }
}

// Provide a suitable constructor (depends on the kind of dataset)
public MyRecycleAdapter() {
     //mDataset = myDataset;
}


@NonNull
@Override
// Create new views (invoked by the layout manager)
public MyRecycleAdapter.ViewHolder onCreateViewHolder(
        @NonNull ViewGroup parent,
        int viewType) {

    LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
    Log.d(TAG, "onCreateViewHolder: layoutInflator = ");

    // create a new view
    View v = layoutInflater.inflate(R.layout.row, parent, false);

    return new ViewHolder(v);
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(final MyRecycleAdapter.ViewHolder viewHolder,
                              final int position) {
    Log.d(TAG, "Element " + position + " set.");

    // - get element from your dataset at this position
    // - replace the contents of the view with that element
    viewHolder.getaCover().setBackgroundColor(Color.RED);
    viewHolder.getAuthor().setText("John Doe, his brothers, his sisters");
    viewHolder.getTitle().setText("The Best Music EVAH1111");
}

@Override
// Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
    return 4;
}
}
  

这是在MainActivity

mRecyclerView = findViewById(R.id.recycler);

    // Setting improve's performance if changes in content don't alter RecyclerView layout size
    mRecyclerView.setHasFixedSize(true);

    // use a linear layout manager
    mLayoutManager = new LinearLayoutManager(MainActivity.this);
    mRecyclerView.setLayoutManager(mLayoutManager);

    // not necessary to achieve goal
    // String[] mew = new String[]{"mew", "two"};

    // specify an adapter (see also next example)
    mAdapter = new MyRecycleAdapter(mew);
    mRecyclerView.setAdapter(mAdapter);

我的问题是当我运行应用程序时,RecyclerView.Adapter onBindViewHolder()无法识别父视图持有者(引用 row.xml )内的子视图....我不知道为什么它没有,因为早些时候没有问题当我运行它插入任何文字或为我的imageview分配一个空,它正确构建,现在它随机调整。我尝试的是,无效/清除缓存并重新启动AS(没有纠正问题),我也尝试创建一个新的虚拟项目并复制并粘贴我的代码,运行它没有任何问题但我在我的主项目中有问题很多文件/辅助类等等......

  

以下是错误日志

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setBackgroundColor(int)' on a null object reference
                  at com.example.android.mediasession.ui.auxillary.MyRecycleAdapter.onBindViewHolder(MyRecycleAdapter.java:67)
                  at com.example.android.mediasession.ui.auxillary.MyRecycleAdapter.onBindViewHolder(MyRecycleAdapter.java:15)
                  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
                  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
                  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
                  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5752)
                  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5748)
                  at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2232)
                  at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1559)
                  at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1519)
                  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:614)
                  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3812)
                  at android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:3225)
                  at android.view.View.measure(View.java:21103)
                  at android.support.constraint.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1210)
                  at android.support.constraint.ConstraintLayout.onMeasure(ConstraintLayout.java:1550)
                  at android.view.View.measure(View.java:21103)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                  at android.view.View.measure(View.java:21103)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1464)
                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:758)
                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:640)
                  at android.view.View.measure(View.java:21103)
                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6462)
                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
                  at com.android.internal.policy.DecorView.onMeasure(DecorView.java:858)
                  at android.view.View.measure(View.java:21103)
                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2573)
                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1632)
                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1883)
                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1512)
                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7094)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:927)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:702)
                  at android.view.Choreographer.doFrame(Choreographer.java:638)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:913)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6836)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

申请已终止。

3 个答案:

答案 0 :(得分:2)

正如@Mike M.在评论中指出的那样,

  

您是否有多个res / layout * /文件夹,您可能在没有这些视图的情况下创建了一行?如果是的话,它们是否与您在上面发布的完全一样;即,所有视图具有完全相同的ID?另外,你是否需要v21 +的不同版本?

我有两个不同的文件夹,包含相同的布局,默认布局文件夹和v21文件夹,但我的视图ID和一些父版LayoutViews不匹配,我更新它们以反映两个文件夹中的精确副本,我的应用程序像魅力一样运行

答案 1 :(得分:1)

你传递了两个值

String[] mew = new String[]{"mew", "two"}; 

并尝试生成4行,这可能会产生indexOutOfBounds异常

@Override
public int getItemCount() {
    return 4;//use your mDataset's size.
}

答案 2 :(得分:1)

在你的onBindViewHolder中有一个小错误,

更新以下代码,我更正了。

viewHolder.aCover.setBackgroundColor(Color.RED);
viewHolder.mAuthor.setText("John Doe, his brothers, his sisters"); viewHolder.mTitle.setText("The Best Music EVAH1111");

你指的是错误的观点。这导致错误。

更新并告知我问题是否得到解决。