天天看點

自定義元件<五>

大家先看一下如何來自定義ViewGroup的:

public class MyGridView extends ViewGroup{

private Context mContext;

public MyGridView(Context context, AttributeSet attrs) {

super(context, attrs);

mContext = context;

myAddView();

}

//注意:onLayout在View中是一個public的方法,在ViewGroup為protected類型,并且為abstract,

//由于這個方法在ViewGroup中沒有實作,是以ViewGroup本身不可以直接使用。

//為子布局設定位置和大小

@Override

protected void onLayout(boolean changed, int l, int t, int r, int b) {

// TODO Auto-generated method stub

View v = getChildAt(0);

// v.layout(l, t, r, b);

v.layout(260, 370, 520,900);

Log.d("yuyahao", "l: " + l+   "t: " + t+   "r: " + r+   "b: " +b+"changed:  " +changed);

}

    public void myAddView(){

        ImageView mIcon = new ImageView(mContext);

        mIcon.setImageResource(R.drawable.ic_launcher);

        addView(mIcon);

    }

//    http://www.spasvo.com/news/html/2013517100523.html

   // 進過研究發現,起作用主要是:來通過調用子View的measure()方法,來确定View的大小。

    @Override

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    // TODO Auto-generated method stub

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

      final int childCount = getChildCount();    //此方法得到該布局下的所有View的個數

    }

   //他的作用主要是确定view在父類中的顯示位置,通過子View的位置計算,條用子view的layout的得到将在複類中的位置設定給View

    @Override

    protected void onLayout(boolean changed, int l, int t, int r, int b) {

    }

}

如果大家認真的讀的話,就會知道自定義元件也是多麼的簡單了吧!

接下老于就教你如如自定義ViewGroup.也會在接下來的環節中如何使用onMeasure()方法,以及onLayout()方法;

 我始終相信: 沒有做不到的,隻有想不到的。

繼續閱讀