简体   繁体   中英

How to retrieve image in on bind view on android?

I have a chat message view in there im displaying user name and image and message, In my message adapter class like below

public void onBindViewHolder(final MessageViewHolder holder, int position) {

        auth = FirebaseAuth.getInstance();
        String currenUserId = auth.getCurrentUser().getUid();
        Message c = mMessageList.get(position);
        String fromUser = c.getFrom();
        reference = FirebaseDatabase.getInstance().getReference().child("Users");

        reference.child(fromUser).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String name = dataSnapshot.child("name").getValue().toString();
                String image = dataSnapshot.child("image").getValue().toString();

                holder.messageName.setText(name);

                if(!image.equals("default")) {
                    Picasso.with().load(image).placeholder(R.drawable.avatar).into(holder.messageProfile);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        holder.messageText.setText(c.getMessage());

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(c.getTime());
        int mHour = calendar.get(Calendar.HOUR_OF_DAY);
        int mMin = calendar.get(Calendar.MINUTE);
        holder.messageTime.setText(mHour+":"+mMin);
    }

im using picasso to retrieve image what should i use as context

您也可以简单地使用这个

Picasso.with(holder.messageProfile.getContext()).load(image).placeholder(R.drawable.avatar).into(holder.messageProfile);

You have to use Context of your parent view of your UserViewHolder as,

public class RecyclerViewAdapter extends 
RecyclerView.Adapter<RecyclerViewAdapter.UserViewHolder>{

private Context context;

@Override
public UserViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    context = parent.getContext();    //use this context with picasso

    return new UserViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_home_screen, parent, false));
}

First declare context in global like

Context context;

After that add in constructor

 this.context = context;  

Use this for Image

 Glide.with(context).load(R.drawable.avatar).into(holder.messageProfile);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM