android 在代碼中設定布局置中layout_gravity,layout_margin的方法

來源:互聯網
上載者:User

標籤:


在代碼中設定布局置中,翻看api可以知道view中有setGravity,setPadding,但是沒有直接的setLayoutGravity,setMargin等方法。下面將在代碼中實作類別似布局中layout_gravity,layout_margin的方法。

可以通過設定view裡面的 LayoutParams 設定,而這個LayoutParams是根據該view在不同的GroupView而不同的。

1、代碼中設定layout_gravity

LinearLayout layoutTop=(LinearLayout) findViewById(R.id.layout_top);FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(layoutTop.getLayoutParams()); params.gravity = Gravity.CENTER_VERTICAL;layoutTop.setLayoutParams(params);

    這裡的FrameLayout、LinearLayout是說明該view在一個FrameLayout或LinearLayout裡面,具體得看自己的布局,這個地方有可能會報錯,比中這樣的錯誤。錯誤很明顯,這也很好解決,只需要按照提示將屬性改為相應的即可。


2、代碼中設定layout_margin

ImageView image = (ImageView) findViewById(R.id.img_icon);  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(image.getLayoutParams());  lp.setMargins(10, 20, 0, 0);  image.setLayoutParams(lp);
該方法可以封裝為:
public static void setMargins (View view, int left, int top, int right, int bottom) {      if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {          ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();          p.setMargins(left, top, right, bottom);          view.requestLayout();      }  }








android 在代碼中設定布局置中layout_gravity,layout_margin的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.