Android LayoutParams使用案例詳解
LayoutParams是什么?
LayoutParams主要保存了一個View的布局參數(shù),因此可以使用LayoutParams來改變布局參數(shù)從而達(dá)到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來實現(xiàn):
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來實現(xiàn),下面是一段獲取設(shè)置Window大小的代碼,例如在自定義Dialog的時候,onCreate方法中編寫這段代碼,從而設(shè)置dialog最后顯示W(wǎng)indow的大小。
Window win = getWindow(); WindowManager.LayoutParams lp = win.getAttributes(); lp.height = DensityUtil.dip2px(mContext, 185); lp.width = DensityUtil.dip2px(mContext, 280); win.setAttributes(lp);
總結(jié)
以上是在開發(fā)過程中用到的一些LayoutParams相關(guān)的內(nèi)容,后期會不斷補充。
到此這篇關(guān)于Android LayoutParams使用案例詳解的文章就介紹到這了,更多相關(guān)Android LayoutParams使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android自定義view實現(xiàn)動態(tài)柱狀圖
這篇文章主要為大家詳細(xì)介紹了Android自定義view實現(xiàn)動態(tài)柱狀圖的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-08-08Android Data Binding數(shù)據(jù)綁定詳解
本文主要介紹Android Data Binding數(shù)據(jù)綁定的知識,這里整理了詳細(xì)的資料及簡單示例代碼幫助大家學(xué)習(xí)理解此部分知識,有需要的小伙伴可以參考下2016-09-09Android使用google breakpad捕獲分析native cash
這篇文章主要介紹了Android使用google breakpad捕獲分析native cash 的相關(guān)知識,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-04-04Android 中自定義ContentProvider與ContentObserver的使用簡單實例
這篇文章主要介紹了Android 中自定義ContentProvider與ContentObserver的使用簡單實例的相關(guān)資料,這里提供實例幫助大家學(xué)習(xí)理解這部分內(nèi)容,需要的朋友可以參考下2017-09-09Android Studio+Servlet+MySql實現(xiàn)登錄注冊
對于大多數(shù)的APP都有登錄注冊這個功能,本文就來介紹一下Android Studio+Servlet+MySql實現(xiàn)登錄注冊,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05