未调用自定义视图构造函数

时间:2014-10-02 14:58:54

标签: android imageview

我创建了CircleImageView以在Circle Shape

显示图像

CircularImageView

public class CircularImageView extends ImageView {

private final static String TAG = "CircularImageView";
private final static float DEFAULT_RADIUS = 90;
private float mRadius;

public CircularImageView(Context context) {
    super(context);
}

public CircularImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public CircularImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircularImageView,defStyle,0);
    mRadius = a.getFloat(R.styleable.CircularImageView_Radius,DEFAULT_RADIUS);
    //Log.i(TAG, String.format("%f", mRadius));
    a.recycle();


}


@Override
protected void onDraw(Canvas canvas) {

    Path path = new Path();

    path.addCircle(getWidth() / 2 ,getHeight() / 2,mRadius,Path.Direction.CW);
    canvas.clipPath(path);
    super.onDraw(canvas);
}

}

现在我在XML文件中使用它

XML文件

           xmlns:app="http://schemas.android.com/apk/res-auto"

            <com.itzik.samara.apps.pokerbuddies.main.back.views.CircularImageView
            android:layout_width="90dp"
            android:layout_height="90dp"
            android:src="@drawable/empty_user_image"
            app:Radius="50"
            android:id="@+id/poker_row_user_image" />

attrs.xml

    <declare-styleable name="CircularImageView">
    <attr name="Radius" format="float" />
</declare-styleable>

首先Android Studio说构造函数没用过? 第二,它不显示图像。 如果我将函数onDraw(Canvas canvas)mRadius更改为数字,则图像工作意味着onDraw()被称为

任何人遇到过这种问题为什么没有调用构造函数?

1 个答案:

答案 0 :(得分:5)

修改此构造函数:

public CircularImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

要:

public CircularImageView(Context context, AttributeSet attrs) {
    //super(context, attrs);

    this(context, attrs, 0);
}