【Android】不知道的 setLayoutParams

來源:互聯網
上載者:User

標籤:android   使用   ar   for   sp   on   c   ad   r   

動態建立Layout的時候,LayoutParams 是必須要設定的參數,關於 setLayoutParams 知道多少呢?

  1. setLayoutParams 是設給父節點的。
    文檔裡說的清楚:

Set the layout parameters associated with this view. These supply parameters to the parent of this view specifying how it should be arranged. There are many subclasses of
ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children.

也就是說這個setLayoutParams()是給其父控制項看的,只有父類可以改變子View的位置布局,而不是說子View可以隨意設定。

  1. setLayoutParams 類型不能隨便給。
    清楚了LayoutParams是根據父節點來設定的,雖然使用的時候建立一個 ViewGroup.LayoutParams 也能夠設定成功,但還是要根據父節點的類型來定義為具體的 RelativeLayout.LayoutParams、LinearLayout.LayoutParams等,否則啟動並執行時候會拋出異常的。

    RelativeLayout.LayoutParams layoutParams= new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);

    view.setLayoutParams(layoutParams);

【Android】不知道的 setLayoutParams

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.