编程时为了方便写了一个抽象类适配器(这种写法是对性能的浪费,不是正确写法,请不要模仿)。
只贴出问题代码,其他略
protected abstract void initData(View itemView, T t, int p);
@Override
public void onBindViewHolder(@NonNull @NotNull VH holder, int position) {
initData(holder.itemView, list.get(position), position);
}
实例化后
Ad<FactoryBean> ad = new Ad<FactoryBean>(list, R.layout.rv_factory) {
private void initView(View iv) {
layGroup = (LinearLayout) iv.findViewById(R.id.layGroup);
img = (ImageView) iv.findViewById(R.id.img);
tv1 = (TextView) iv.findViewById(R.id.tv1);
tv2 = (TextView) iv.findViewById(R.id.tv2);
tv3 = (TextView) iv.findViewById(R.id.tv3);
tv4 = (TextView) iv.findViewById(R.id.tv4);
tv5 = (TextView) iv.findViewById(R.id.tv5);
bar = (BarChart) iv.findViewById(R.id.bar);
}
private BarChart bar;
private TextView tv5;
private TextView tv4;
private TextView tv3;
private TextView tv2;
private TextView tv1;
private ImageView img;
private LinearLayout layGroup;
@Override
protected void initData(View itemView, FactoryBean d, int p) {
initView(itemView);
layGroup.setOnClickListener(v -> {
Log.i("TAG", "initData: " + d.getIconUrl());
if (bar.getVisibility() == View.VISIBLE)
bar.setVisibility(View.INVISIBLE);
else
bar.setVisibility(View.VISIBLE);
});
}
};
由于变量可能没有及时更新,导致点击控件时bar控件不会隐藏和显示。这种情况下只要在方法内进行控件查找即可解决。
@Override
protected void initData(View iv, FactoryBean d, int p) {
LinearLayout layGroup = (LinearLayout) iv.findViewById(R.id.layGroup);
ImageView img = (ImageView) iv.findViewById(R.id.img);
TextView tv1 = (TextView) iv.findViewById(R.id.tv1);
TextView tv2 = (TextView) iv.findViewById(R.id.tv2);
TextView tv3 = (TextView) iv.findViewById(R.id.tv3);
TextView tv4 = (TextView) iv.findViewById(R.id.tv4);
TextView tv5 = (TextView) iv.findViewById(R.id.tv5);
BarChart bar = (BarChart) iv.findViewById(R.id.bar);
tv1.setText(d.getMaterialName());
layGroup.setOnClickListener(v -> {
Log.i("TAG", "initData: " + d.getIconUrl());
if (bar.getVisibility() == View.VISIBLE)
bar.setVisibility(View.INVISIBLE);
else
bar.setVisibility(View.VISIBLE);
});
}