日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

androidstudio图片居中_android 在代码中设置布局居中layout_gravity,layout_margin的方法...

發布時間:2024/3/24 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 androidstudio图片居中_android 在代码中设置布局居中layout_gravity,layout_margin的方法... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在代碼中設置布局居中,翻看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();

}

}

總結

以上是生活随笔為你收集整理的androidstudio图片居中_android 在代码中设置布局居中layout_gravity,layout_margin的方法...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。