长按隐藏工具栏



我想在适配器类中隐藏长按时的工具栏。但无论我选择什么方式,它总是给我错误的尝试调用虚拟方法'void androidx.appcompat.widget.Toolbar.setVisibility(int)' on a null object reference或类似的东西。这是我的方法

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{
androidx.appcompat.widget.Toolbar toolbar;
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.main,parent,false);
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int  position) {
holder.item.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
MenuItem menuItem  = mode.getMenu().findItem(R.id.my_toolbar);
menuItem.setVisible(false); or
toolbar = view.findViewById(R.id.my_toolbar);
toolbar.setVisibility(View.GONE);

,这是存在工具栏的片段活动的XML文件。

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".FragmentOne">
<androidx.appcompat.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:listitem="@layout/main"
android:id="@+id/RV"/>
</androidx.constraintlayout.widget.ConstraintLayout>

这里有一些问题,根据您的评论,似乎view变量正在为onCreateViewHolder上的每一行重新分配,因此,当涉及到onBindViewHolder时,您无法保证当前引用与您绑定的视图相关。相反,您应该从视图holder中检索绑定视图,例如:

holder.itemView

无论如何,您希望找到Toolbar,它驻留在与RecyclerView相同的片段中,通过在RecyclerView的子节点上调用findViewById。如果你看一下findViewById的文档或源代码,你可以看到它向下遍历视图层次结构,寻找匹配的子视图,所以它永远不会到达你的Toolbar


一个肮脏的解决方案是在设置RecyclerView时传递对Toolbar的引用,但建议的方法是传递回调到适配器,这可以由片段设置,并在长时间单击itemView时调用。

最新更新