Android自定義控件使用到XML的時候報錯no such method

今天自定義一個View

繼承ImageView,然後用在XML裏
自定義的類如下

public class MyView extends ImageView{

    public MyView(Context context) {
        // TODO Auto-generated constructor stub
        super(context);
             ObjectAnimator colorAnim = (ObjectAnimator)  AnimatorInflater.loadAnimator(context,R.animator.testanim);
         colorAnim.setEvaluator( new ArgbEvaluator());
         colorAnim.setTarget(this);
         colorAnim.start();
    }
}

XML引用如下(包名是正確的)

 <com.weikang.customView.MyView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/img"/>

運行報錯.解析XML的時候出錯,no such method

仔細看 原因加載構造器的時候報錯的

在ImageView裏有三個構造器,

public ImageView(Context context) {
        super(context);
        initImageView();
    }

    public ImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

我只重寫了第一個,no such method報錯是說第二個

原因:解析XML的時候會用到第二個構造器

如果直接在代碼裏new 就不報錯了

一定要在XML裏用就要重寫第二個構造器

public class MyView extends ImageView{

    public MyView(Context context,AttributeSet attr) {
        // TODO Auto-generated constructor stub
        super(context,attr);
         ObjectAnimator colorAnim = (ObjectAnimator) AnimatorInflater.loadAnimator(context,R.animator.testanim);
         colorAnim.setEvaluator( new ArgbEvaluator());
         colorAnim.setTarget(this);
         colorAnim.start();
    }
}

好了 可以放心食用了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章