对于 NetworkImageView 定义了一个名为的变量,mDefaultImageId
您可以使用它来定义默认图像的资源
这是你可以做到的 -
创建一个名为 的文件attrs.xml
,在其中放置以下行 -
<declare-styleable name="DefaultImageResId">
<attr name="default_image_resource" format="reference" />
</declare-styleable>
创建一个名为CustomNetworkImageView
并使用以下代码的类 -
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import com.android.volley.toolbox.NetworkImageView;
import com.myapp.R;
public class CustomNetworkImageView extends NetworkImageView {
public CustomNetworkImageView(Context context) {
super(context);
}
public CustomNetworkImageView(Context context, AttributeSet attrs) {
super(context, attrs);
setDefaultImageResId(context, attrs);
}
public CustomNetworkImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setDefaultImageResId(context, attrs);
}
private void setDefaultImageResId(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.DefaultImageResId);
int resId = typedArray.getResourceId(R.styleable.DefaultImageResId_default_image_resource, 0);
if (0 != resId)
setDefaultImageResId(resId);
}
}
现在在您的常规布局 xml 文件中像这样使用 -
<com.myapp.CustomNetworkImageView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:default_image_resource="@drawable/defaultimage"/>
请记住,行在xmlns:app="http://schemas.android.com/apk/res-auto"
布局文件的根元素中非常重要然后添加app:default_image_resource
你完了!!!现在您甚至可以从您的 xml 中提及图像