要根据每个元素更改Drawable资源的颜色,您可以使用ColorFilter类。以下是一个示例代码,该代码演示如何更改ListView中的每个元素的Drawable资源的颜色。
首先,创建一个自定义的ArrayAdapter类来填充ListView:
public class CustomAdapter extends ArrayAdapter {
private Context mContext;
private int mResourceId;
private List mItems;
private int mColor;
public CustomAdapter(Context context, int resourceId, List items, int color) {
super(context, resourceId, items);
mContext = context;
mResourceId = resourceId;
mItems = items;
mColor = color;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(mResourceId, null);
}
// 获取Drawable资源
Drawable drawable = mContext.getResources().getDrawable(R.drawable.your_drawable_resource);
// 设置颜色过滤器
drawable.setColorFilter(mColor, PorterDuff.Mode.SRC_IN);
// 设置Drawable到ImageView或其他视图中
ImageView imageView = view.findViewById(R.id.image_view);
imageView.setImageDrawable(drawable);
// 设置文本
TextView textView = view.findViewById(R.id.text_view);
textView.setText(mItems.get(position));
return view;
}
}
然后,在您的Activity中使用此自定义适配器类来填充ListView:
public class MainActivity extends AppCompatActivity {
private ListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
List items = new ArrayList<>();
items.add("Item 1");
items.add("Item 2");
items.add("Item 3");
int color = Color.parseColor("#FF0000"); // 更改为您想要的颜色
CustomAdapter adapter = new CustomAdapter(this, R.layout.list_item, items, color);
mListView.setAdapter(adapter);
}
}
上述代码中,您需要替换以下内容:
R.drawable.your_drawable_resource
:将其替换为您要更改颜色的Drawable资源。R.id.image_view
:将其替换为您ListView中包含Drawable的视图的ID。R.id.text_view
:将其替换为您ListView中显示文本的视图的ID。Color.parseColor("#FF0000")
:将其替换为您想要的颜色的十六进制表示。