簡體   English   中英

以編程方式在Android中設置視圖高度

[英]Setting View height programmatically Android

我用公共方法定義了一個自定義視圖:

public void setHeight(int height) {
    //this.getLayoutParams().height = height; --- NOT WORKING
    this.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, height)); // --- WORKING

當我使用注釋掉的代碼時,它不起作用(這意味着調用此方法時視圖高度沒有改變),但是當我使用第二個短語時,它按預期工作。

有什么可以解釋這種行為?

這很容易-只需看一下setLayoutParams()的代碼即可:

 public void setLayoutParams(ViewGroup.LayoutParams params) {
     if (params == null) {
         throw new NullPointerException("Layout parameters cannot be null");
     }
     mLayoutParams = params;
     if (mParent instanceof ViewGroup) {
         ((ViewGroup) mParent).onSetLayoutParams(this, params);
     }
     requestLayout();
 }

看到? 設置布局參數后,它將調用requestLayout()

順便說一句:可以在www.grepcode.com上找到Android源代碼,它通常很有幫助。

暫無
暫無

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

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