[英]create and set margin programmatic for relative layout android
嗨,我正在開發android應用程序,其中我以編程方式創建相對布局,並嘗試為此設置邊距並將其添加到具有線性方向的線性布局中。 所以這是我的代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/screen_background"
tools:context=".ChooseChannelsFragment" >
<LinearLayout
android:id="@+id/main_outer_llt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
>
</LinearLayout>
</RelativeLayout>
在片段內部,我要像這樣添加相對布局
RelativeLayout relativeLayout = new RelativeLayout(getActivity());
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(200, 80);
relativeParams.setMargins(20, 20, 20, 20);
relativeLayout.setLayoutParams(relativeParams);
relativeLayout.setBackgroundColor(getResources().getColor(R.color.green_color));
linearLayout.addView(relativeLayout);
它使用給定的顏色和大小創建布局,但不接受邊距。 難道我做錯了什么? 這個怎么做? 需要幫忙。 謝謝。
您在視圖上使用的LayoutParams類型實際上應該來自其父級。
因此,如果要將RelativeLayout添加到LinearLayout,則設置為RelativeLayout的LayoutParams實際上應該是LinearLayout.LayourParams,而不是RelativeLayout.LayoutParams。
就像其他人建議的那樣,layout_margin#是父級的#邊緣和您的視圖之間的空間。
獲得/設置利潤對我有用:
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) mView.getLayoutParams();
params.topMargin += 20;
mView.requestLayout(); // important
當然,我的View確實是一個ViewGroup,父級也是一個ViewGroup。 在大多數情況下,應將布局參數轉換為父級的View類LayoutParams(在這種情況下為ViewGroup和RelativeLayout)
在這種情況下,父親是LinearLayout。 因此,您應該使用:
TableLayout.LayoutParams layoutParams = new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT, TableLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(20, 20, 20, 20);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.