Android addView()方法分爲以下幾個部分
addView()方法簡述(一)
addView()方法實際使用和麪試手冊(二)
本章簡介
本章將針對上文提到的addView()的方法進行實例操作,並就可能出現的問題以面試題的方式進行解答。
1 .addView (View child, ViewGroup.LayoutParams params)
這個方法是將第二個參數指定的佈局給第一個參數傳入的子視圖中。
聽上去有點拗口,我們先看例子,然後再解析
//1
RelativeLayout mRelativeLayout= findViewById(R.id.rl_base);
//2
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//3
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(this);
textView.setText("I love China");
linearLayout.addView(textView);
//4
mRelativeLayout.addView(linearLayout,layoutParams);
看上面這部分代碼第一部分獲取了一個RelativeLayout。第二部分創建了一個RelativeLayout的LayoutParams並向其中添加了兩個規則,一個是在父佈局的最右面,一個是再父佈局的最底部。第三部分則創建了一個LinearLayout然後向其中添加了一個TextView。第四部分再通過addView (View child, ViewGroup.LayoutParams params)方法吧LinearLayout添加進了RelativeLayout。(注:RelativeLayout的寬和高都是Match_Parent)然後我們來看圖
被添加的LinearLayout確實已經被添加進了RelativeLayout的右下方。我們換一種寫法再來看看
linearLayout.setLayoutParams(layoutParams);
mRelativeLayout.addView(linearLayout);
我們把最後一個方法換成了如上的兩行代碼再來運行看看結果
一模一樣,這樣我們就知道了官方描述的意思了。addView (View child, ViewGroup.LayoutParams params)這個方法是將第二個參數賦予了第一個參數然後進行了添加的工作。
這裏有的同學就不動了,明明我的ViewGroup是LinearLayout爲什麼可以set一個RelativeLayout的LayoutParams?看看下面這道面試題。
面試題
1.RelativeLayout的LayoutParams可以賦予LinearLayout嗎?LayoutParams是對於誰而言的?
答案:RelativeLayout的LayoutParams是可以賦予LinearLayout的,前提是我們要把LinearLayout作爲子View添加進RelativeLayout,否則如果是別的父View添加進去是沒有效果的。
LayoutParams是相對於父佈局而言的,我們添加給不同View的LayoutParams都要父佈局來解析。當然了,獲取自身的LayoutParams之後也可以修改自己View的寬高邊距等參數,但是這些都是相對的。
2.addView (View child, int index)
這個方法是將傳入的子視圖放在父佈局的指定位置。
一個豎向的LinearLayout,如果你把index指定爲-1則每次都會把子視圖放在最後一個,也就是一個一個向下疊加,新加入的會放在最後;如果把Index指定爲0,新加入的將會在頭部把先加入的子視圖擠下去,達到在頂部插入視圖的效果,以此類推,具體看效果。
LinearLayout
TextView textView = new TextView(this);
textView.setText("textView");
TextView textView1 = new TextView(this);
textView1.setText("textView1");
TextView textView2 = new TextView(this);
textView2.setText("textView2");
LinearLayout linearLayout1 = new LinearLayout(this);
linearLayout1.setOrientation(LinearLayout.VERTICAL);
linearLayout.addView(textView,-1);
linearLayout.addView(textView1,-1);
linearLayout.addView(textView2,-1);
我們把index置爲-1
可以看到是按照順序往下加的,和addView (View child)的效果是一樣的;
我們把index置位0
和我們的預期一致
需要注意的是,index參數的大小不能大於子View的個數,不然會報錯。
Caused by: java.lang.IndexOutOfBoundsException: index=1 count=0
如果我們設置的index大於子view的個數會有問題,猜想一下子View是怎麼存儲的呢?
3.addView (View child, int index,ViewGroup.LayoutParams params)
這個就是前兩個的一個結合,不多說了。
4.addView (View child)
需要注意的是,這個會吧父佈局的佈局信息添加給這個子視圖。所以,如果你想這個子視圖有自己的佈局信息,就要先通過setLayoutParams設置好佈局信息再addView。
5.addView (View child, int width, int height)
這個看上去就很容易,通過width和height來指定子視圖的寬高。
總結
這篇主要介紹了LayoutParams的使用,學會了這一點就OK了,在日常的使用中就沒有大問題了!好啦,addView的文章到這就結束了!