adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );此代码生成错误,我无法解决错误

Posted

技术标签:

【中文标题】adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );此代码生成错误,我无法解决错误【英文标题】:adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) ); this code generates error & i am unable to solve error 【发布时间】:2020-05-10 12:19:45 【问题描述】:

adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );这条线产生错误&我对这个错误的了解很低。两个所需的 java 文件和详细的错误在这两个 java 文件之后给出。


ImageAdapter.java

package com.example.login;

import android.content.Context;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.squareup.picasso.Picasso;

import java.util.List;

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ImageViewHolder> 

    private Context Context;
    private List<Upload> Uploads;
    private OnItemClickListener Listener;


    public ImageAdapter (Context context, List<Upload> uploads1)
        Context = context;
        Uploads = uploads1;
    
    @NonNull
    @Override
    public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) 
        View v= LayoutInflater.from(Context).inflate(R.layout.image_item, parent, false);
        return new ImageViewHolder(v);
    

    @Override
    public void onBindViewHolder(@NonNull ImageViewHolder holder,int position) 
        Upload uploadCurrent= Uploads.get(position);
        holder.textViewName.setText(uploadCurrent.getName());
        Picasso.with(Context)
                .load(uploadCurrent.getImageUrl())
                .placeholder(R.drawable.logo)
                .fit()
                .centerInside()
                .into(holder.imageView);
    

    @Override
    public int getItemCount() 
        return Uploads.size();
    

    public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
            View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener 

        public TextView textViewName;
        public ImageView imageView;

        public ImageViewHolder(@NonNull View itemView) 
            super(itemView);
            textViewName = itemView.findViewById(R.id.text_product_name);
            imageView = itemView.findViewById(R.id.product_image);

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

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

        @Override
        public void onCreateContextMenu(ContextMenu menu,View v,ContextMenu.ContextMenuInfo menuInfo) 
            menu.setHeaderTitle("Select Action");
            MenuItem details = menu.add(Menu.NONE ,1,1,"Details");
            MenuItem delete = menu.add(Menu.NONE ,2,2,"Delete");

            details.setOnMenuItemClickListener(this);
            delete.setOnMenuItemClickListener(this);
        

        @Override
        public boolean onMenuItemClick(MenuItem item) 
            if(Listener != null)
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) 
                    switch(item.getItemId())
                        case 1:
                            Listener.OnDetailsClick(position);
                            return true;

                        case 2:
                            Listener.OnDeleteClick(position);
                            return true;
                    
                
            
            return false;
        
    

    public interface OnItemClickListener
        void OnItemClick(int Position);

        void OnDetailsClick(int Position);

        void OnDeleteClick(int Position);
    
    public void SetOnClickItemListener(OnItemClickListener listener)
        Listener = listener;
    


MyAddsFragment.java

package com.example.login.ui.login;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.login.ImageAdapter;
import com.example.login.R;
import com.example.login.Upload;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;
import java.util.List;

public class MyAddsFragment extends Fragment implements ImageAdapter.OnItemClickListener

    private RecyclerView recyclerView;
    private ImageAdapter adapter;
    private ProgressBar progressBar;
    private DatabaseReference databaseRef;
    private List<Upload> Uploads;
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        View v =  inflater.inflate(R.layout.fragment_myadds, container, false);

        recyclerView = v.findViewById(R.id.Recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        progressBar = v.findViewById(R.id.progress_bar_1);
        Uploads = new ArrayList<>();

        databaseRef = FirebaseDatabase.getInstance().getReference("uploads");
        databaseRef.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
                    Upload upload = postSnapshot.getValue(Upload.class);
                    Uploads.add(upload);
                
                adapter = new ImageAdapter(getActivity(), Uploads);
                recyclerView.setAdapter(adapter);

                adapter.SetOnClickItemListener((ImageAdapter.OnItemClickListener) getActivity());

                progressBar.setVisibility(View.INVISIBLE);
            

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) 
                Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
                progressBar.setVisibility(View.INVISIBLE);
            
        );
        return v;
    

    @Override
    public void OnItemClick(int Position) 
        Toast.makeText(getActivity(),"Normal Click Position:"+Position,Toast.LENGTH_SHORT).show();
    

    @Override
    public void OnDetailsClick(int Position) 
        Toast.makeText(getActivity(),"Details Click Position:"+Position,Toast.LENGTH_SHORT).show();
    

    @Override
    public void OnDeleteClick(int Position) 
        Toast.makeText(getActivity(),"Delete Click Position:"+Position,Toast.LENGTH_SHORT).show();
    


错误如下

01-24 12:33:27.072 6252-6252/com.example.login E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.login, PID: 6252
    java.lang.ClassCastException: com.example.login.HomeActivity cannot be cast to com.example.login.ImageAdapter$OnItemClickListener
        at com.example.login.ui.login.MyAddsFragment$1.onDataChange(MyAddsFragment.java:57)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.0:55)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

.................................................. ..................................................... ...

【问题讨论】:

【参考方案1】:

你的班级MyAddsFragment 正在实现ImageAdapter.OnItemClickListener,所以设置adapter.SetOnClickItemListener 你可以简单地使用下面的代码 -

adapter.SetOnClickItemListener(MyAddsFragment.this)

您不能将 ImageAdapter.OnItemClickListener 转换为 HomeActicity.class,因为它可能无法实现。

【讨论】:

MyAddsFragment.java 不是活动。它是一个片段。 & Fragment 不像活动。 是的,但 MyAddsFragment 正在实现接口 OnItemClickListener,因此您必须使用 adapter.SetOnClickItemListener(MyAddsFragment.this)。要在 HomeActivity 中使用 OnItemClickListener,您必须在 home Activity 中实现接口 OnItemClickListener 以便您可以像当前一样使用 - adapter.SetOnClickItemListener((HomeActivity)getActivity()) 很抱歉和你争论..你是绝对正确的。错误已解决...?????? 没问题很乐意帮忙:)

以上是关于adapter.setOnClickItemListener ( (ImageAdapter.OnItemClickListener) getActivity( ) );此代码生成错误,我无法解决错误的主要内容,如果未能解决你的问题,请参考以下文章