簡體   English   中英

Android以編程方式設置底邊距

[英]Android set bottom margin programmatically

是否可以使用RelativeLayout.LayoutParams指定對象的底部邊距? 我只想指定底部邊距。

這樣嘗試。

TextView mTvLine = findViewById(R.id.tv_line);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
// add rule
params.addRule(RelativeLayout.ALIGN_BOTTOM,R.id.ll_status);
params.setMargins(0, 0, 0, 0);
mTvLine.setLayoutParams(params);

注意

RelativeLayout.LayoutParams relativeLayoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

// Child widget relative to the widget: imageViewId is ABOVE of it
relativeLayoutParams.addRule(RelativeLayout.ABOVE, imageViewId.getId());

// Child widget relative to the widget: imageViewId is BELOW of it
relativeLayoutParams.addRule(RelativeLayout.BELOW, imageViewId.getId());

//  Child widget relative to the widget: aligned with the bottom of the imageViewId
relativeLayoutParams.addRule(RelativeLayout.ALIGN_BOTTOM, imageViewId.getId());

// The following three methods represent the same, indicating that the child widget is at the bottom of the parent widget
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, -1);//
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
relativeLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);  

是可以的,但這可能表明您可以以更適當的方式完成您想做的事情。 那么,此請求背后的原因是什么?

如果您確實需要以編程方式而不是通過xml布局來執行此操作,則可以執行以下操作:

View myView = findViewById(R.layout.my_view);
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
params.bottomMargin = 23;  // your new value, in pixels
view.setLayoutParams(params);

需要注意的兩個細節:邊距以像素為單位,而xml布局以dps為單位; 此外,對於每種視圖類型,您都需要轉換為自己的特定布局參數類型。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM