【发布时间】:2016-04-10 12:35:49
【问题描述】:
我有一个RecyclerView,每行都有一个图标。图标应该是动态着色的,所以我使用白色图标并在绑定视图时应用颜色过滤器。奇怪的是,我最终在结果视图中发现了很多差异。
在本例中,我尝试将每第三行设置为红色,其余为绿色(注意 #18):
下面是适配器。如您所见,每次我重新绑定支架时,我都会将更改后的图标应用于ImageView,大概没有为旧的回收图像留出空间。
public class TestAdapter extends RecyclerView.Adapter<TestAdapter.ViewHolder> {
private final Context context;
public TestAdapter(Context context) {
this.context = context;
}
@Override
public TestAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(TestAdapter.ViewHolder holder, int position) {
holder.bindItem(position);
}
@Override
public int getItemCount() {
return 200;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final ImageView image;
private final TextView text;
public ViewHolder(View itemView) {
super(itemView);
image = (ImageView) itemView.findViewById(R.id.image);
text = (TextView) itemView.findViewById(R.id.text);
}
public void bindItem(int position) {
// pick color depending on the position
final int color = ContextCompat.getColor(context,
position%3 == 0 ? android.R.color.holo_red_light : android.R.color.holo_green_light
);
// set text content and color
text.setText("#" + position);
text.setTextColor(color);
// create icon from the resource and set filter
final Drawable icon = ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_brightness, null);
icon.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
image.setImageDrawable(icon);
}
}
}
item_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/image"
android:layout_width="18dp"
android:layout_height="wrap_content"
android:scaleType="fitStart"
android:adjustViewBounds="true" />
<TextView
android:id="@+id/text"
android:textSize="18sp"
android:textColor="@android:color/black"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
tools:text="text" />
</LinearLayout>
什么给了?
谢谢。
【问题讨论】:
-
如果你想要不同类型的视图,而不是选择位置,考虑覆盖
getItemViewType方法。 -
问题是在实际项目中颜色可能是任意的,它来自服务器。
-
这很有趣。您是否使用不同的图标而不是过滤器对此进行了测试,看看您是否仍然得到相同的结果?
-
@PPartisan 是的,它适用于不同的图标。
标签: android imageview android-recyclerview porter-duff