结果证明代码具有以下形式:
@Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
startActivity(new Intent(this, Information.class));
}
});
}
分别:
startActivity(new Intent(this, Information.class));
她不想在这里工作。
我提供了完整的适配器代码:
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Phone> phones;
public DataAdapter(Context context, List<Phone> phones) {
this.phones = phones;
this.inflater = LayoutInflater.from(context);
}
@Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.list_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
startActivity(new Intent(this, Information.class));
}
});
}
@Override
public int getItemCount() {
return phones.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
final ImageView imageView;
final TextView nameView, companyView;
final Button button;
ViewHolder(View view){
super(view);
imageView = (ImageView)view.findViewById(R.id.image);
nameView = (TextView) view.findViewById(R.id.name);
companyView = (TextView) view.findViewById(R.id.company);
button = (Button) view.findViewById(R.id.button);
}
}
}
这是实际的问题。我该如何从适配器打开新活动……谢谢。
答案 0 :(得分:0)
请勿将传递的上下文处理到您的适配器
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private LayoutInflater inflater;
private List<Phone> phones;
private Context context;
public DataAdapter(Context context, List<Phone> phones) {
this.context = context;
this.phones = phones;
this.inflater = LayoutInflater.from(context);
}
// Remainder code
}
然后使用context
开始新活动
@Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
final Phone phone = phones.get(position);
holder.imageView.setImageResource(phone.getImage());
holder.nameView.setText(phone.getName());
holder.companyView.setText(phone.getCompany());
holder.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("click: ", phone.getClickbutton());
context.startActivity(new Intent(this, Information.class));
}
});
}