ItemClickListener在onclick上在Fragment RecyclerView中不起作用

时间:2018-10-21 21:31:16

标签: java android android-studio android-fragments android-recyclerview

我一直在关注本教程:Tutorial 为了用onclick制作一个json recyclerviewer,但是我想使用Fragments代替活动。

我已经弄清楚了一切,直到点击完成为止。

我的问题是 setOnItemClickListener 没有使用我的 getActivity() 我已经做了很多尝试,但是我看不到明亮的光线。

如果有人可以帮助我,那就太好了!

我唯一真正的问题是getActivity在以下位置出现红线:

  

fNieuwsAdapter.setOnItemClickListener( getActivity());

NieuwsFragment.java

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;

    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;

    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import org.jsoup.Jsoup;

    import java.util.ArrayList;

    public class NieuwsFragment extends Fragment implements NieuwsAdapter.OnItemClickListener {
        public static final String EXTRA_URL = "nieuwsImageUrl";
        public static final String EXTRA_HEADING = "nieuwsHeading";
        public static final String EXTRA_CONTENT = "nieuwsContent";

        private RecyclerView fNieuwsRecyclerView;
        private NieuwsAdapter fNieuwsAdapter;
        private ArrayList<NieuwsItem> fNieuwsList;
        private RequestQueue fNieuwsQueue;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_nieuws, container, false);
            fNieuwsRecyclerView = view.findViewById(R.id.recycler_view);
            fNieuwsRecyclerView.setHasFixedSize(true);
            fNieuwsRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

            fNieuwsList = new ArrayList<>();

            fNieuwsQueue = Volley.newRequestQueue(getActivity());
            parseJSON();
            return view;
        }

        private void parseJSON() {
            String url = "urlissecretsorry<3butthejsonparsingworks";

            JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                    new Response.Listener<JSONObject>() {
                        public String nieuwsImageUrl;
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                JSONArray jsonArray = response.getJSONArray("posts");

                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject hit = jsonArray.getJSONObject(i);
                                    JSONArray attachArray = hit.getJSONArray("attachments");
                                    for (int a = 0; a < attachArray.length(); a++) {
                                        JSONObject attach = attachArray.getJSONObject(a);
                                        nieuwsImageUrl = attach.getString("url");
                                    }

                                    String nieuwsHeading = hit.getString("title");
                                    String nieuwsExcerpt = hit.getString("excerpt");
                                    String nieuwsContent = hit.getString("content");
                                    nieuwsExcerpt = html2text(nieuwsExcerpt);


                                    fNieuwsList.add(new NieuwsItem(nieuwsImageUrl, nieuwsHeading, nieuwsExcerpt,nieuwsContent));
                                }

                                fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList);
                                fNieuwsAdapter.setOnItemClickListener(getActivity());
                                fNieuwsRecyclerView.setAdapter(fNieuwsAdapter);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });

            fNieuwsQueue.add(request);
        }
        @Override
        public void onItemClick(int position) {
            Intent detailIntent = new Intent(getActivity(), DetailActivity.class);
            NieuwsItem clickedItem = fNieuwsList.get(position);

            detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
            detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
            detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());

            startActivity(detailIntent);
        }

        public String html2text(String html) {
            try {
                return Jsoup.parse(html).text();
            } catch (Exception ignored) {
                return "";
            }
        }
    }

NieuwsItem.java

    public class NieuwsItem {
        private String nieuwsImageUrl;
        private String nieuwsHeading;
        private String nieuwsExcerpt;
        private String nieuwsContent;

        public NieuwsItem(String imageUrl, String heading, String excerpt, String content){
            nieuwsImageUrl = imageUrl;
            nieuwsHeading = heading;
            nieuwsExcerpt = excerpt;
            nieuwsContent = content;
        }

        public String getImageUrl(){
            return nieuwsImageUrl;
        }
        public String getHeading(){
            return nieuwsHeading;
        }
        public String getExcerpt(){
            return nieuwsExcerpt;
        }
        public String getContent(){
            return nieuwsContent;
        }
    }

NieuwsAdapter.java

 import android.content.Context;
    import android.support.annotation.NonNull;
    import android.support.v7.widget.RecyclerView;
    import android.support.v4.app.FragmentActivity;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;
    import android.widget.TextView;

    import com.squareup.picasso.Picasso;

    import java.util.ArrayList;

    public class NieuwsAdapter extends RecyclerView.Adapter<NieuwsAdapter.NieuwsViewHolder> {

        private Context NieuwsContext;
        private ArrayList<NieuwsItem> NieuwsList;
        private OnItemClickListener NieuwsListener;

        public interface OnItemClickListener {
            void onItemClick(int position);
        }

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

        public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
            NieuwsContext = context;
            NieuwsList = nieuwslist;
        }

        @NonNull
        @Override
        public NieuwsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(NieuwsContext).inflate(R.layout.nieuws_item, parent, false);
            return new NieuwsViewHolder(v);
        }

        @Override
        public void onBindViewHolder(NieuwsViewHolder holder, int position) {
            NieuwsItem currentitem = NieuwsList.get(position);

            String ImageUrl = currentitem.getImageUrl();
            String Heading = currentitem.getHeading();
            String Excerpt = currentitem.getExcerpt();

            holder.NieuwsTextViewHeading.setText(Heading);
            holder.NieuwsTextViewExcerpt.setText(Excerpt);
            Picasso.get().load(ImageUrl).fit().centerInside().into(holder.NieuwsImageView);
        }

        @Override
        public int getItemCount() {

            return NieuwsList.size();
        }

        public class NieuwsViewHolder extends RecyclerView.ViewHolder {

            public ImageView NieuwsImageView;
            public TextView NieuwsTextViewHeading;
            public TextView NieuwsTextViewExcerpt;

            public NieuwsViewHolder(@NonNull View itemView) {
                super(itemView);

                NieuwsImageView = itemView.findViewById(R.id.nieuws_image);
                NieuwsTextViewHeading = itemView.findViewById(R.id.nieuws_heading);
                NieuwsTextViewExcerpt = itemView.findViewById(R.id.nieuws_excerpt);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (NieuwsListener != null) {
                            int position = getAdapterPosition();
                            if (position != RecyclerView.NO_POSITION) {
                                NieuwsListener.onItemClick(position);
                            }
                        }
                    }
                });
            }
        }
    }

DetailActivity.java

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

public class DetailActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        Intent intent = getIntent();
        String imageUrl = intent.getStringExtra("EXTRA_URL");
        String creatorName = intent.getStringExtra("EXTRA_HEADING");
        String likeCount = intent.getStringExtra("EXTRA_CONTENT");

        ImageView imageView = findViewById(R.id.nieuws_detail_image);
        TextView textViewHeading = findViewById(R.id.nieuws_detail_heading);
        TextView textViewContent = findViewById(R.id.nieuws_detail_content);

        Picasso.get().load(imageUrl).fit().centerInside().into(imageView);
        textViewHeading.setText(creatorName);
        textViewContent.setText("Likes: " + likeCount);
    }
}

2 个答案:

答案 0 :(得分:0)

更改

public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist) {
        NieuwsContext = context;
        NieuwsList = nieuwslist;
    }

public NieuwsAdapter(Context context, ArrayList<NieuwsItem> nieuwslist, OnItemClickListener mOnClickListener) {
        this.NieuwsContext = context;
        this.NieuwsList = nieuwslist;
        this.NieuwsListener = mOnClickListener;
    }

还有这个

itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (NieuwsListener != null) {
                        int position = getAdapterPosition();
                        if (position != RecyclerView.NO_POSITION) {
                            NieuwsListener.onItemClick(position);
                        }
                    }
                }
            });

更改为

itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                   NieuwsListener.onItemClick(int position); 
                }
            });

然后在片段中您可以这样

fNieuwsAdapter = new NieuwsAdapter(getActivity(), fNieuwsList,new NieuwsAdapter.OnItemClickListener() {
        @Override
        public void onItemClick(int position)
        {
            //DoSomethingHere
        }
  });

答案 1 :(得分:0)

您不能使用NieuwsAdapter.setOnItemClickListener(getActivity());,除非您的活动实现了OnItemClickListener接口,但是我看到您的片段实现了OnItemClickListener,所以您可以像这样使用该片段:

fNieuwsAdapter.setOnItemClickListener(NieuwsFragment.this);

顺便说一句,您正在通过意图通过

发送数据:
detailIntent.putExtra(EXTRA_URL, clickedItem.getImageUrl());
detailIntent.putExtra(EXTRA_HEADING, clickedItem.getHeading());
detailIntent.putExtra(EXTRA_CONTENT, clickedItem.getContent());

您必须使用相同的参数获取它们(删除“”):

 String imageUrl = intent.getStringExtra(EXTRA_URL);
 String creatorName = intent.getStringExtra(EXTRA_HEADING);
 String likeCount = intent.getStringExtra(EXTRA_CONTENT);

希望这会有所帮助