在我的主要活动中,我有简单的方法,我想在内部适配器中执行,但我的view.getContext()
得到错误的类,我不能这样做,
我的活动:
public class UnfoldableDetailsActivity extends AppCompatActivity {
private View listTouchInterceptor;
private View detailsLayout;
private UnfoldableView unfoldableView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unfoldable_details);
ListView listView = Views.find(this, R.id.list_view);
listView.setAdapter(new PaintingsAdapter(this));
...
}
@Override
public void onBackPressed() {
...
}
public void openDetails(View coverView, Painting painting) {
...
}
}
如您所见,我通过以下方式将上下文设置为适配器:
ListView listView = Views.find(this, R.id.list_view);
listView.setAdapter(new PaintingsAdapter(this));
现在在这个适配器中我必须从onClick
获得正确的上下文:
public class PaintingsAdapter extends ItemsAdapter<Painting> implements View.OnClickListener {
public PaintingsAdapter(Context context) {
super(context);
setItemsList(Arrays.asList(Painting.getAllPaintings(context.getResources())));
}
@Override
protected View createView(Painting item, int pos, ViewGroup parent, LayoutInflater inflater) {
...
return view;
}
@Override
protected void bindView(Painting item, int pos, View convertView) {
...
}
@Override
public void onClick(View view) {
Painting item = (Painting) view.getTag(R.id.list_item_image);
if (view.getContext() instanceof UnfoldableDetailsActivity) {
((UnfoldableDetailsActivity) view.getContext()).openDetails(view, item);
}
}
private static class ViewHolder {
...
}
}
view.getContext()
返回TintContextWrapper
,必须为UnfoldableDetailsActivity
且错误
答案 0 :(得分:0)
像这样改写:
public class PaintingsAdapter extends ItemsAdapter<Painting> implements View.OnClickListener {
UnfoldableDetailsActivity parentActivity;
public PaintingsAdapter(UnfoldableDetailsActivity parentActivity) {
super(context);
this.parentActivity = parentActivity;
setItemsList(Arrays.asList(Painting.getAllPaintings(context.getResources())));
}
@Override
public void onClick(View view) {
Painting item = (Painting) view.getTag(R.id.list_item_image);
parentActivity.openDetails(view, item);
}
}
现在你不再需要施放。