LayoutParams基本使用

LayoutParams是什麼?

LayoutParams主要保存了一個View的佈局參數,因此可以使用LayoutParams來改變佈局參數從而達到View位置的效果,一般在自定義View的時候使用。

LayoutParams怎麼用?

  • 如果父控件是LinearLayout,需要使用LinearLayout.LayoutParams
    代碼如下:
LinearLayout.LayoutParams layoutParams=(LinearLayout.LayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams)
  • 如果父控件是RelativeLayout的話,需要使用RelativeLayout.LayoutParams。
RelativeLayout.LayoutParams layoutParams=(RelativeLayout.LayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams)
  • 除了使用佈局的LayoutParams外,我們還可以用ViewGroup.MarginLayoutParams來實現:
ViewGroup.MarginLayoutParams layoutParams=(ViewGroup.MarginLayoutParams)getLayoutParams();
layoutParams.leftMargin=getLeft()+offsetX;
layoutParams.topMargin=getTop()+offsetY;
setLayoutParams(layoutParams);
  • 對於一些不需要尋找父View,自己new出一個View自定義的情況。
View line = null;
LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
layoutParams.leftMargin = 10;
line = new View(mContext);
line.setBackgroundResource(R.color.color_tie_bg);
addView(line, layoutParams);
  • 通過WindowManager.LayoutParams來實現,下面是一段獲取設置Window大小的代碼,例如在自定義Dialog的時候,onCreate方法中編寫這段代碼,從而設置dialog最後顯示Window的大小。
 Window win = getWindow();
        WindowManager.LayoutParams lp = win.getAttributes();
        lp.height = DensityUtil.dip2px(mContext, 185);
        lp.width = DensityUtil.dip2px(mContext, 280);
        win.setAttributes(lp);

總結

以上是在開發過程中用到的一些LayoutParams相關的內容,後期會不斷補充。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章