如何解决适配器上的setOnClickListener

时间:2019-06-04 12:42:26

标签: android fragment

我在片段中有此方法

public void setOnItemClickListener(OnItemClickListener listener){
    mListener = listener;
}

,我喜欢在另一个片段中使用此方法, 像这样

listImageAdapter.setOnItemClickListener(context);

但是出现错误,因为参数是OnItemClickListener, 我看了他们这样使用的教程, 因为他们在Activity而不是片段上使用了

mAdapter.setOnItemClickListener(ImagesActivity.this);

那么,我该如何解决呢?

贝洛是我的完整代码

ListFragment

public class ListFragment extends BaseFragment implements ListImageAdapter.OnItemClickListener {

    public static final String TAG = "ListFragment";

    private RecyclerView recyclerViewImages;
    private DatabaseReference databaseReference;
    private Context context;

    private List<Model> mModel;
    private ListImageAdapter listImageAdapter;
    private Variable staticVariable = new Variable();

    public ListFragment() {

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_batik, container, false);
        findView(view);
        initView(view);
        initListener(view);
        getDataFromFirebase();
        return view;
    }

    private void getDataFromFirebase() {
        recyclerViewImages.setHasFixedSize(true);
        recyclerViewImages.setLayoutManager(new LinearLayoutManager(context));
        mModel = new ArrayList<>();
        databaseReference = FirebaseDatabase.getInstance().getReference(staticVariable.BATIK_DETECTIONS);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    Model model = postSnapshot.getValue(Model.class);
                    mModel.add(model);
                }
                listImageAdapter = new ListImageAdapter(context, mModel);
                listImageAdapter.setOnItemClickListener(context); // this is where i got an error
                recyclerViewImages.setAdapter(listImageAdapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                simpleActivity.toastMessage(context, databaseError.getMessage());
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void findView(View view) {
        recyclerViewImages = view.findViewById(R.id.recycleview_image);

    }

    @Override
    public void initView(View view) {

    }

    @Override
    public void initListener(View view) {

    }

    @Override
    public void OnItemClick(int position) {

    }

    @Override
    public void OnViewDescriptions(int position) {

    }

    @Override
    public void OnEditItem(int position) {

    }
}

ListImageAdapter

public class ListImageAdapter extends RecyclerView.Adapter<ListImageAdapter.ImageViewHolder>  {

    private Context context;
    private List<Model> mModels;
    private OnItemClickListener mListener;

    public ListImageAdapter(Context context, List<Model> mModels) {
        this.context = context;
        this.mModels = mModels;
    }

    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_images, viewGroup, false);
        return new ImageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder imageViewHolder, int position) {
        Model model = mModels.get(position);
        imageViewHolder.textView.setText(model.getImageNames());
        Picasso.get()
                .load(model.getImagesUri())
                .placeholder(R.mipmap.ic_launcher)
                .fit()
                .centerCrop()
                .into(imageViewHolder.imageView);

    }

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

    class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
            View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener {
        private ImageView imageView;
        private TextView textView;

        public ImageViewHolder(@NonNull View itemView) {
            super(itemView);
            textView = itemView.findViewById(R.id.tv_images_name);
            imageView = itemView.findViewById(R.id.list_images);

            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        }

        @Override
        public boolean onMenuItemClick(MenuItem item) {
            if (mListener != null) {
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) {

                    switch (item.getItemId()) {
                        case 1:
                            mListener.OnViewDescriptions(position);
                            return true;
                        case 2:
                            mListener.OnEditItem(position);
                            return true;
                    }
                }
            }
            return false;
        }

        @Override
        public void onClick(View v) {
            if(mListener!=null){
                int position = getAdapterPosition();
                if(position != RecyclerView.NO_POSITION){
                    mListener.OnItemClick(position);
                }
            }

        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.setHeaderTitle("Select Actions");
            MenuItem ViewDescribtions = menu.add(Menu.NONE, 1, 1, "Lihat Deskripsi");
            MenuItem Edit = menu.add(Menu.NONE, 2, 2, "Edit");

            ViewDescribtions.setOnMenuItemClickListener(this);
            Edit.setOnMenuItemClickListener(this);
        }
    }

    public interface OnItemClickListener{
        void OnItemClick(int position);
        void OnViewDescriptions(int position);
        void OnEditItem(int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener){
        mListener = listener;
    }
}

3 个答案:

答案 0 :(得分:1)

如果上下文是这样定义的

Context context;
...
...
context = this;

然后,这将不起作用,因为setOnItemClickListener正在等待ListFragment类,而不是Context

如果您在片段的onCreateView中进行设置,则可以这样

listImageAdapter.setOnItemClickListener(this);

listImageAdapter.setOnItemClickListener(ListFragment.this);

答案 1 :(得分:0)

您的界面,

interface ItemClickListener {
fun onItemClick(position: Int)

}

您的适配器类,

public class InnerAdapter extends RecyclerView.Adapter<InnerAdapter.InnerViewHolder> {

private Context context;
private ItemClickListener listener;

public InnerAdapter(Context context, ItemClickListener listener) {
    this.context = context;
    this.listener = listener;
}

@NonNull
@Override
public InnerAdapter.InnerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View holder = LayoutInflater.from(context)
            .inflate(R.layout.item_inneradapter, viewGroup, false);
    return new InnerViewHolder(holder);
}

@Override
public void onBindViewHolder(@NonNull InnerViewHolder innerViewHolder, final int i) {
    innerViewHolder.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            listener.onItemClick(i);
        }
    });
}

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


class InnerViewHolder extends RecyclerView.ViewHolder {

    public TextView textView;

    public InnerViewHolder(View itemView) {
        super(itemView);
        textView = itemView.findViewById(R.id.textView);
    }
}

}

您的活动

class NestedRecyclerActivity : AppCompatActivity() ,ItemClickListener{

override fun onItemClick(position: Int) {
    Log.e("yourItemClickPosition :", "" + position)
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_nested_recycler)

    recyclerOuter.layoutManager = LinearLayoutManager(
        this, LinearLayoutManager.VERTICAL, false
    )
    recyclerOuter.isNestedScrollingEnabled = false
    val adapter = InnerAdapter(this,this)
    recyclerOuter.adapter = adapter
}

}

答案 2 :(得分:0)

setOnItemClickListener()在这里定义:

public void setOnItemClickListener(OnItemClickListener listener){
    mListener = listener;
}

但是当您需要一个Context时,您在此处传递了一个OnItemClickListener参数。

listImageAdapter.setOnItemClickListener(context);

您的片段实现了interface

public class ListFragment extends BaseFragment implements ListImageAdapter.OnItemClickListener

因此,您可以仅将this作为参数传递(其中this指向Fragment的当前实例):

listImageAdapter.setOnItemClickListener(this);