將自定義設計時屬性新增到 NetworkImageView
Volley NetworkImageView
增加了標準 ImageView
的其他幾個屬性。但是,這些屬性只能在程式碼中設定。以下是如何建立擴充套件類的示例,該擴充套件類將從 XML 佈局檔案中獲取屬性並將它們應用於 NetworkImageView
例項。
在~/res/xml
目錄中,新增名為 attrx.xml
的檔案:
<resources>
<declare-styleable name="MoreNetworkImageView">
<attr name="defaultImageResId" format="reference"/>
<attr name="errorImageResId" format="reference"/>
</declare-styleable>
</resources>
將新類檔案新增到專案中:
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);
}
}
}
顯示自定義屬性使用的示例佈局檔案:
<?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>