意图和开始活动不适用于recyclerview Adapter

时间:2015-09-21 14:51:33

标签: android android-intent android-activity

吐司适用于onClick(),没有别的,我也在AndroidManifest中完成了所有参赛作品

IntentstartActivity无法在onClick()适配器RecyclerView上工作,而Toast工作正常

这是我的代码

public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.MyForecastViewHolder> {
public Context context;

private LayoutInflater inflator;

List<Information> data = Collections.emptyList();

public ForecastAdapter(Context context, List<Information> data) {
    inflator = LayoutInflater.from(context);
    this.data = data;
    this.context = context;
}

@Override
public MyForecastViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = inflator.inflate(R.layout.custom_row_forecast, parent, false);
    MyForecastViewHolder holder = new MyForecastViewHolder(view);
    return holder;
}

@Override
public void onBindViewHolder(MyForecastViewHolder holder, final int position) {
    Information current = data.get(position);
    holder.title.setText(current.title);
    holder.icon.setImageResource(current.iconId);
}


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

class MyForecastViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView title;
    ImageView icon;

    public MyForecastViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        title = (TextView) itemView.findViewById(R.id.temp);
        icon = (ImageView) itemView.findViewById(R.id.listIcon3);
    }

    @Override
    public void onClick(View v) {
        context.startActivity(new Intent(context,SubActivity.class));
    }
}
}

1 个答案:

答案 0 :(得分:2)

您如何知道这样点击过哪个位置? 您应该将clickListener更改为onBindView方法,该方法可以为您提供单击的位置并将其设置在根布局上。

类似的东西:

class MyForecastViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView title;
    ImageView icon;

    public MyForecastViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        title = (TextView) itemView.findViewById(R.id.temp);
        icon = (ImageView) itemView.findViewById(R.id.listIcon3);
        yourRootView = (LayoutType) itemView.findViewById(R.id.root);
    }

    @Override
    public void onClick(View v) {
        context.startActivity(new Intent(context,SubActivity.class));
    }
}

@Override
public void onBindViewHolder(MyForecastViewHolder holder, final int position) {
    Information current = data.get(position);
    holder.title.setText(current.title);
    holder.icon.setImageResource(current.iconId);
    holder.yourRootView.setTag(position); // get it after with getTag()
    holder.yourRootView.setOnClickListener(this);
}