我有一个形状,我需要使用以下代码更改颜色:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
LockListDataModel locks = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_row, parent, false);
viewHolder.lockName = (TextView) convertView.findViewById(R.id.lockName);
viewHolder.colour = (ImageView) convertView.findViewById(R.id.list_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}// Populate the data into the template view using the data object
viewHolder.lockName.setText(locks.lockName);
viewHolder.colour.setVisibility(View.VISIBLE);
viewHolder.colour.setBackground(ResourcesCompat.getDrawable(getContext().getResources(), R.drawable.time_profile_shape, null));
LayerDrawable shape = (LayerDrawable) ContextCompat.getDrawable(getContext(),R.drawable.time_profile_shape);
GradientDrawable color = (GradientDrawable)(shape.findDrawableByLayerId(R.id.time_profile_lock_colour));
color.setColor(Color.parseColor(locks.color));
// Return the completed view to render on screen
return convertView;
}
作为参考,形状如下所示:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:left="2dp" android:top="2dp">
<shape android:shape="rectangle" android:padding="10dp">
<solid android:color="@color/colorPrimaryDark"></solid>
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
</item>
<item android:right="2dp" android:bottom="2dp" android:id="@+id/time_profile_lock_colour">
<shape android:shape="rectangle" android:padding="10dp" >
<solid android:color="@color/backgroundColour"></solid>
<corners
android:bottomRightRadius="5dp"
android:bottomLeftRadius="5dp"
android:topLeftRadius="5dp"
android:topRightRadius="5dp"/>
</shape>
</item>
这是为列表视图填充自定义列表适配器,并且适用于除 21 和 22(棒棒糖)之外的所有 API 级别 18(最低 SDK)+。
API 18 = 工作,颜色变化
API 19 = 工作,颜色变化
API 21 = 颜色不变
API 22 = 颜色不变
API 23 = 工作,颜色变化
我怎样才能让它在棒棒糖上工作?
谢谢