主要是出于测试目的,我希望能够通过单击我在ViewHolder中为RecyclerView引用的imageView来创建Toast消息,但我无法弄清楚如何将其传递给上下文。任何帮助,将不胜感激。
package com.checkinsystems.ez_score.utils;
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.checkinsystems.ez_score.R;
import com.checkinsystems.ez_score.Sample.TestActivity;
import com.checkinsystems.ez_score.model.Match;
import java.util.List;
public class MatchItemAdapter extends RecyclerView.Adapter<MatchItemAdapter.ViewHolder> {
private List<Match> mMatches;
private Context mContext;
public MatchItemAdapter(Context context, List<Match> items){
this.mContext = context;
this.mMatches = items;
}
@Override
public MatchItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View itemView = inflater.inflate(R.layout.list_item_match, parent, false);
ViewHolder viewHolder = new ViewHolder(itemView);
return viewHolder;
}
@Override
public void onBindViewHolder(MatchItemAdapter.ViewHolder holder, int position) {
Match match = mMatches.get(position);
try {
holder.tvName.setText(match.getMatchName());
holder.tvDate.setText(match.getMatchDate());
holder.imageView.findViewById(R.id.imageView);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return mMatches.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public TextView tvName;
public TextView tvDate;
public ImageView imageView;
public ViewHolder(View itemView){
super(itemView);
tvName = (TextView)itemView.findViewById(R.id.match_name);
tvDate = (TextView)itemView.findViewById(R.id.match_date);
imageView = (ImageView)itemView.findViewById(R.id.imageView);
imageView.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Toast.makeText(, "onClick working", Toast.LENGTH_LONG).show();
}
});
}
}
}
从我收集到的内容中,您无法从不扩展Activity类的内容中调用Toast消息,但必须有某种类型的解决方法。
答案 0 :(得分:0)
使用view.getContext()
public void onClick(View view) {
Toast.makeText(view.getContext(), "onClick working", Toast.LENGTH_LONG).show();
}