I have a LinearLayout xml with a RecyclerView:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/r1"
android:background="#DBDBDB">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#DBDBDB" />
</LinearLayout>
In my java class I am setting the background image of whole Linearlayout:
LinearLayout linear;
linear = findViewById(R.id.r1);
linear.setBackgroundResource(R.drawable.visitedbg);
This is working fine. But I want to set background for the Linearlayout also in Recycleradapter.
In the list the user can remove any item by clicking on it. And if the last item is removed, I want to show a background image.
In onBindViewHolder
method I have:
movieList.remove(position);notifyDataSetChanged();
if (getItemCount()<=0){holder.linear.setBackgroundResource(R.drawable.visitedbg);}
Problem is the Nullpointerexception, as I can't define the LinearLayout view in Recycleradapter.
I tried to put it to public MyviewHolder(View itemView)
, also in public RecyclerAdapter.MyviewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
as
LinearLayout linear = itemView.findViewById(R.id.r1);
but this is still not working. Is there any solution for this?
First of all, I recommend migrating from findViewById() to viewBindng to prevent app from crashing in running time. Second, You can only access views inside recyclerView's items from adapter. to implement what you want, you should listen for recyclerView's adapter change. You can use AdapterDataObserver:
adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
super.onItemRangeRemoved(positionStart, itemCount);
//...
}
});
Take a look at this link in android documentation.
Another way to achieve that will be checking for adapter's item count everytime you remove an element:
movieList.remove(position);
notifyItemRemoved(position);
if(adapter.getItemCount() == 0)
linear.setBackgroundResource(R.drawable.visitedbg)