Adding custom design time attributes to NetworkImageView
suggest changeThere are several additional attributes that the Volley NetworkImageView
adds to the standard ImageView
. However, these attributes can only be set in code. The following is an example of how to make an extension class that will pick up the attributes from your XML layout file and apply them to the NetworkImageView
instance for you.
In your ~/res/xml
directory, add a file named attrx.xml
:
<resources>
<declare-styleable name="MoreNetworkImageView">
<attr name="defaultImageResId" format="reference"/>
<attr name="errorImageResId" format="reference"/>
</declare-styleable>
</resources>
Add a new class file to your project:
package my.namespace;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import com.android.volley.toolbox.NetworkImageView;
public class MoreNetworkImageView extends NetworkImageView {
public MoreNetworkImageView(@NonNull final Context context) {
super(context);
}
public MoreNetworkImageView(@NonNull final Context context, @NonNull final AttributeSet attrs) {
this(context, attrs, 0);
}
public MoreNetworkImageView(@NonNull final Context context, @NonNull final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.MoreNetworkImageView, defStyle, 0);
// load defaultImageResId from XML
int defaultImageResId = attributes.getResourceId(R.styleable.MoreNetworkImageView_defaultImageResId, 0);
if (defaultImageResId > 0) {
setDefaultImageResId(defaultImageResId);
}
// load errorImageResId from XML
int errorImageResId = attributes.getResourceId(R.styleable.MoreNetworkImageView_errorImageResId, 0);
if (errorImageResId > 0) {
setErrorImageResId(errorImageResId);
}
}
}
An example layout file showing the use of the custom attributes:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<my.namespace.MoreNetworkImageView
android:layout_width="64dp"
android:layout_height="64dp"
app:errorImageResId="@drawable/error_img"
app:defaultImageResId="@drawable/default_img"
tools:defaultImageResId="@drawable/editor_only_default_img"/>
<!--
Note: The "tools:" prefix does NOT work for custom attributes in Android Studio 2.1 and
older at least, so in this example the defaultImageResId would show "default_img" in the
editor, not the "editor_only_default_img" drawable even though it should if it was
supported as an editor-only override correctly like standard Android properties.
-->
</android.support.v7.widget.CardView>
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents