在TaskListActivity类中覆盖editTask方法,该类实现了OnEditTask接口
为什么我们使用上下文并将其转换为OnEditTask接口?
我在这里缺少什么接口或java的原理?
这是“Android应用开发傻瓜”一书中的代码。
RecyclerView适配器
完整的RecyclerView适配器代码
package com.example.manis.tasks.adapter;
import android.content.Context;
import android.support.v7.widget.CardView;
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.example.manis.tasks.activity.R;
import com.example.manis.tasks.interfaces.OnEditTask;
import com.squareup.picasso.Picasso;
public class TaskListAdapter extends RecyclerView.Adapter<TaskListAdapter.ViewHolder>
{
static String[] fakeData = new String[]
{
"One","Two","Three","Four","Five","Ah....ah..ah"
};
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
CardView v = (CardView) LayoutInflater.from(parent.getContext()).inflate(R.layout.card_task, parent, false);
return new ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position)
{
final Context context = viewHolder.titleView.getContext();
viewHolder.titleView.setText(fakeData[position]);
Log.v("myTag",fakeData[position].toString());
Picasso.with(context)
.load(getImageUrlForTask(position))
.into(viewHolder.imageView);
viewHolder.cardView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
((OnEditTask)context).editTask(position);
}
});
}
@Override
public int getItemCount()
{
return fakeData.length;
}
static class ViewHolder extends RecyclerView.ViewHolder
{
CardView cardView;
TextView titleView;
ImageView imageView;
public ViewHolder(CardView card)
{
super(card);
cardView=card;
titleView = (TextView) card.findViewById(R.id.text1);
imageView = (ImageView) card.findViewById(R.id.image);
}
}
public static String getImageUrlForTask(long taskId){
return "http://lorempixel.com/600/400/cats/?fakeId=" + taskId;
}
}
答案 0 :(得分:1)
在实现OnEditTask接口的TaskListActivity类中重写editTask方法
这就解释了为什么需要演员。否则你无法调用该方法
它可以预先投射,就像在这一行
final Context context = viewHolder.titleView.getContext();
可能是
final OnEditTask onEditTask = (OnEditTask) viewHolder.titleView.getContext();
但在其他地方需要Context变量(对毕加索来说)
Picasso.with(context)
.load(getImageUrlForTask(position))
.into(viewHolder.imageView);