在卡片视图内的图像视图上添加点击事件

时间:2016-05-27 07:47:38

标签: android android-recyclerview

我为我的回收站视图编写了适配器和卡片视图。但是我遇到了问题。如何在卡片视图中的图片视图(“delete_img”)上添加点击事件。

comment_post.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground"
    android:orientation="vertical">

    <de.hdodenhof.circleimageview.CircleImageView
        android:id="@+id/comment_profile_pic"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="20dp"
        android:src="@drawable/ic_profile" />

    <TextView
        android:id="@+id/comment_profile_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="12dp"
        android:layout_toRightOf="@+id/comment_profile_pic"
        android:text="မင်းထက်ဦး"
        android:textColor="#0f0f0f"
        android:textSize="17dp" />



    <TextView
        android:id="@+id/comment_date"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/comment_detail"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:layout_toRightOf="@+id/comment_profile_pic"
        android:text="leleee"
        android:textColor="#bab7b7"
        android:textSize="12dp" />


    <TextView
        android:id="@+id/comment_detail"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/comment_profile_name"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="7dp"
        android:layout_toRightOf="@+id/comment_profile_pic"
        android:text="ဘယ်ကလမ်းပျက်ရမှာလဲ. ​အလုပ်မရှိ​အား​အား​ရား​ရား"
        android:textColor="#0f0f0f"
        android:textSize="14dp" />

    <View
        android:id="@+id/divider"
        android:layout_width="match_parent"
        android:layout_height="0.7sp"
        android:layout_below="@+id/comment_date"
        android:layout_marginLeft="2sp"
        android:layout_marginRight="2sp"
        android:layout_marginTop="12dp"
        android:background="@android:color/darker_gray"
        android:paddingTop="5sp" />
    <ImageView
        android:layout_alignParentRight="true"
        android:id="@+id/delete_img"
        android:src="@drawable/delete_comment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


</RelativeLayout>

DetailPostAdapter.java

package fixmystreet.teamyolo.net.pyinpaypar.Adapters;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
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.List;

import de.hdodenhof.circleimageview.CircleImageView;
import fixmystreet.teamyolo.net.pyinpaypar.Gson.Comment;
import fixmystreet.teamyolo.net.pyinpaypar.MainApplication;
import fixmystreet.teamyolo.net.pyinpaypar.R;

/**
 * Created by tayote on 5/9/16.
 */
public class DetailPostAdapter extends RecyclerView.Adapter<DetailPostAdapter.DetailPostViewHolder> {

    List<Comment> commentList;
    Context context;
    CommentClickListener commentClickListener;


    public DetailPostAdapter(Context context, List<Comment> commentList,CommentClickListener commentClickListener) {
        this.context = context;
        this.commentList = commentList;
        this.commentClickListener = commentClickListener;
    }

    @Override
    public DetailPostViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.comment_post, parent, false);
        return new DetailPostViewHolder(view);
    }

    @Override
    public void onBindViewHolder(DetailPostViewHolder holder, int position) {
        holder.commentProfileName.setTypeface(MainApplication.typefaceManager.getUnicode());
        holder.commentDetail.setTypeface(MainApplication.typefaceManager.getUnicode());
        holder.commentProfileName.setText(this.commentList.get(position).getUser_name() + " ");
        holder.commentDetail.setText(this.commentList.get(position).getComment()+" ");
        holder.commentDate.setText(this.commentList.get(position).getCommentDate());
        Picasso.with(context).load("https://graph.facebook.com/" + this.commentList.get(position).getUserInfoList().get(0).getSocial_id() + "/picture?type=large").placeholder(R.drawable.ic_profile).into(holder.commentProfilePic);
        Log.i("mmm", this.commentList.get(position).getUserInfoList().get(0).getSocial_id());
    }

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

    public class DetailPostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        CircleImageView commentProfilePic;
        TextView commentProfileName;
        TextView commentDetail;
        TextView commentDate;
        ImageView delete_img;

        public DetailPostViewHolder(View itemView) {
            super(itemView);
            commentProfilePic = (CircleImageView) itemView.findViewById(R.id.comment_profile_pic);
            commentProfileName = (TextView) itemView.findViewById(R.id.comment_profile_name);
            commentDetail = (TextView) itemView.findViewById(R.id.comment_detail);
            commentDate = (TextView) itemView.findViewById(R.id.comment_date);
            delete_img = (ImageView) itemView.findViewById(R.id.delete_img);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            if(commentList!=null){
                commentClickListener.onItemClicked(commentList.get(getLayoutPosition()));
            }
        }
    }

    public interface CommentClickListener{
        public void onItemClicked(Comment itemClicked);
    }


}

DetailPost.java

package fixmystreet.teamyolo.net.pyinpaypar;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.securepreferences.SecurePreferences;
import com.squareup.picasso.Picasso;

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

import de.hdodenhof.circleimageview.CircleImageView;
import fixmystreet.teamyolo.net.pyinpaypar.Adapters.DetailPostAdapter;
import fixmystreet.teamyolo.net.pyinpaypar.Api.CommentApi;
import fixmystreet.teamyolo.net.pyinpaypar.Api.DetailPostApi;
import fixmystreet.teamyolo.net.pyinpaypar.Api.LikeCountApi;
import fixmystreet.teamyolo.net.pyinpaypar.Api.MainService;
import fixmystreet.teamyolo.net.pyinpaypar.Gson.Comment;
import fixmystreet.teamyolo.net.pyinpaypar.Gson.PostDetail;
import fixmystreet.teamyolo.net.pyinpaypar.Utilties.FinalResult;
import fixmystreet.teamyolo.net.pyinpaypar.Utilties.Helper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class DetailPost extends AppCompatActivity implements DetailPostAdapter.CommentClickListener {

    Bundle bundle;
    List<Comment> commentList = new ArrayList<>();
    NotScrollableRecyclerView commentRecycler;
    DetailPostAdapter detailPostAdapter;
    Button moreComment;
    public SecurePreferences sharedPreferences;
    public int commentPostId;

    FloatingActionButton iconLike;
    FloatingActionButton iconChat;

    private TextView detailPostToolbarTitle;

    TextView ownerPostTxt;
    TextView postDateTxt;
    ImageView postPic;
    CircleImageView profilePic;
    FloatingActionButton fabIconLike;
    TextView locationTxt;
    TextView reportTxt;
    TextView descriptionTxt;

    RelativeLayout mRelativeLayout;

    static boolean flag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_post);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        setTitle("");

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        detailPostToolbarTitle = (TextView) findViewById(R.id.detail_post_toolbar_title);
        detailPostToolbarTitle.setText("အ\u200B\u200Bသေးစိတ်ကြည့်ရှု့ရန်");
        detailPostToolbarTitle.setTypeface(MainApplication.typefaceManager.getUnicode());

        MyLinearLayoutManager layoutManager =
                new MyLinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        moreComment = (Button) findViewById(R.id.more_comment);
        moreComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle args = new Bundle();
                args.putInt("post_id", FinalResult.postId);
                Intent i = new Intent(DetailPost.this, AllComment.class);
                i.putExtras(args);
                startActivity(i);
            }
        });

        iconLike = (FloatingActionButton) findViewById(R.id.icon_like);
        iconChat = (FloatingActionButton) findViewById(R.id.icon_discuss);
        ownerPostTxt = (TextView) findViewById(R.id.post_owner_txt);
        postDateTxt = (TextView) findViewById(R.id.post_date_txt);
        postPic = (ImageView) findViewById(R.id.post_pic);
        profilePic = (CircleImageView) findViewById(R.id.profile_pic);
        fabIconLike = (FloatingActionButton) findViewById(R.id.icon_like);
        locationTxt = (TextView) findViewById(R.id.location_txt);
        reportTxt = (TextView) findViewById(R.id.report_txt);
        descriptionTxt = (TextView) findViewById(R.id.description_txt);
        mRelativeLayout = (RelativeLayout) findViewById(R.id.post_header);
        commentRecycler = (NotScrollableRecyclerView) findViewById(R.id.comment_rv);
        moreComment = (Button) findViewById(R.id.more_comment);

        moreComment.setTypeface(MainApplication.typefaceManager.getUnicode());

        downloadPostDetail(FinalResult.postId);
        detailPostAdapter = new DetailPostAdapter(getApplicationContext(), commentList, this);
        commentRecycler.setLayoutManager(layoutManager);
        commentRecycler.setAdapter(detailPostAdapter);

        iconLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!flag) {
                    Picasso.with(getApplicationContext()).load(R.drawable.ic_thumb_up).into(iconLike);
                    Call<HashMap<String, String>> hashMapCall = LikeCountApi.createService(MainService.class).sendLikeCount(MainApplication.securedUserId, FinalResult.postId, 1);
                    hashMapCall.enqueue(new Callback<HashMap<String, String>>() {
                        @Override
                        public void onResponse(Call<HashMap<String, String>> call, Response<HashMap<String, String>> response) {
                            Log.i("nnn", response.message() + " false");
                        }

                        @Override
                        public void onFailure(Call<HashMap<String, String>> call, Throwable t) {
                            Log.i("lll", t.toString());
                        }
                    });
                    flag = true;
                } else {
                    Picasso.with(getApplicationContext()).load(R.drawable.ic_action_name).into(iconLike);
                    Call<HashMap<String, String>> hashMapCall = LikeCountApi.createService(MainService.class).sendLikeCount(MainApplication.securedUserId, FinalResult.postId, 0);
                    hashMapCall.enqueue(new Callback<HashMap<String, String>>() {
                        @Override
                        public void onResponse(Call<HashMap<String, String>> call, Response<HashMap<String, String>> response) {
                            Log.i("nnn", response.message()+" true");
                        }

                        @Override
                        public void onFailure(Call<HashMap<String, String>> call, Throwable t) {
                            Log.i("lll", t.toString());
                        }
                    });
                    flag = false;
                }
            }
        });
        iconChat.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LayoutInflater layoutInflater = LayoutInflater.from(DetailPost.this);
                View promptView = layoutInflater.inflate(R.layout.prompts, null);
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(DetailPost.this);
                alertDialogBuilder.setView(promptView);

                TextView promptText = (TextView) promptView.findViewById(R.id.prompt_textview);
                promptText.setTypeface(MainApplication.typefaceManager.getUnicode());
                final EditText editText = (EditText) promptView.findViewById(R.id.editTextDialogUserInput);
                // setup a dialog window
                alertDialogBuilder.setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                String comment = editText.getText().toString();
                                if(Helper.zgDetector(comment)){
                                    comment = Helper.ZawgyiToUnicode(comment);
                                    sharedPreferences = new SecurePreferences(getApplicationContext());
                                    SharedPreferences.Editor editor = sharedPreferences.edit();
                                    // 0 = zawgyi, 1 = unicode
                                    editor.putInt("font", 0);
                                    editor.commit();
                                }
                                postComment(FinalResult.postId, MainApplication.securedUserId, comment);
                                downloadPostDetail(FinalResult.postId);
                            }
                        })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // create an alert dialog
                AlertDialog alert = alertDialogBuilder.create();
                alert.show();
            }
        });

        mRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPostOwner();
            }
        });
    }

    private void showPostOwner() {
        Intent i = new Intent(DetailPost.this, fixmystreet.teamyolo.net.pyinpaypar.UserInfo.class);
        startActivity(i);
    }

    private void downloadPostDetail(final int postId) {
        commentList.clear();
        Call<PostDetail> postDetailCall = DetailPostApi.createService(MainService.class).getComments(postId);
        postDetailCall.enqueue(new Callback<PostDetail>() {
            @Override
            public void onResponse(Call<PostDetail> call, Response<PostDetail> response) {
                commentPostId = Integer.parseInt(response.body().getId());
                FinalResult.userId = response.body().getOwner_id();

                ownerPostTxt.setTypeface(MainApplication.typefaceManager.getUnicode());
                postDateTxt.setTypeface(MainApplication.typefaceManager.getUnicode());
                locationTxt.setTypeface(MainApplication.typefaceManager.getUnicode());
                reportTxt.setTypeface(MainApplication.typefaceManager.getUnicode());
                descriptionTxt.setTypeface(MainApplication.typefaceManager.getUnicode());

                ownerPostTxt.setText(response.body().getOwner_name());
                postDateTxt.setText(response.body().getPostDate());
                Picasso.with(getApplicationContext()).load(response.body().getPost_image()).into(postPic);
                Picasso.with(getApplicationContext()).load("https://graph.facebook.com/" + response.body().getFuck_id() + "/picture?type=large").placeholder(R.drawable.ic_profile).into(profilePic);
                locationTxt.setText(response.body().getLocation());
                reportTxt.setText(response.body().getCause());
                descriptionTxt.setText(response.body().getDescription());
                flag = response.body().isLiked();
                if (flag) {
                    Picasso.with(getApplicationContext()).load(R.drawable.ic_thumb_up).into(iconLike);
                    Log.i("Hello", response.body().isLiked() + " yay");
                } else {
                    Log.i("Hello", response.body().isLiked() + " shit");
                    Picasso.with(getApplicationContext()).load(R.drawable.ic_action_name).into(fabIconLike);
                }
                if (!response.body().getCommentList().isEmpty()) {
                    commentList.addAll(response.body().getCommentList());
                }
                detailPostAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<PostDetail> call, Throwable t) {

            }
        });
    }

    @Override
    public void onItemClicked(Comment itemClicked) {
        FinalResult.userId = itemClicked.getUser_id();
        Log.i("id", FinalResult.userId);
        Intent i = new Intent(this, fixmystreet.teamyolo.net.pyinpaypar.UserInfo.class);
        startActivity(i);
    }

    public void postComment(int commentPostId, String userId, String comment) {
        Log.i("sss", commentPostId + " " + userId + " " + comment);
        Call<HashMap<String, String>> mapCall = CommentApi.createService(MainService.class).comment(commentPostId, userId, comment);
        mapCall.enqueue(new Callback<HashMap<String, String>>() {
            @Override
            public void onResponse(Call<HashMap<String, String>> call, Response<HashMap<String, String>> response) {
                Log.i("fuck u", response.body().toString() + "");
            }

            @Override
            public void onFailure(Call<HashMap<String, String>> call, Throwable t) {

            }
        });
    }
}

2 个答案:

答案 0 :(得分:1)

改变这个:

delete_img = (ImageView) itemView.findViewById(R.id.delete_img);
delete_img.setOnClickListener(this);

更改您的onclick方法,如下所示:

        @Override
        public void onClick(View v) {
            if(commentList!=null){
                commentClickListener.onItemClicked(commentList.get(getLayoutPosition()));
            }
            if (v.getId() == R.id.delete_img) {
            //do here
            }
        }

答案 1 :(得分:0)

好像你做对了,不是你的

 @Override
    public void onClick(View v) {
        if(commentList!=null){  
            commentClickListener.onItemClicked(commentList.get(getLayoutPosition()));
        }
    }

被叫?或者确实:

commentList.get(getLayoutPosition())

不行吗?如果是这样,您可以尝试将其更改为:

commentList.get(getAdapterPosition())