我正在尝试以编程方式RelativeLayout在我的活动中添加一个上边距.使用xml我可以在这种模式下执行:android:layout_marginTop="10dp"但是当我尝试以编程方式执行时没有任何更改...正如您所看到的,我RelativeLayout在一个LinearLayout容器中使用了一些(有一个for循环).
这是我正在使用的代码:
//LINEAR LAYOUT
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
for (int i=1; i<=3; i++){
//RELATIVE LAYOUT
RelativeLayout relativeLayout = new RelativeLayout(this);
relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT,
RelativeLayout.LayoutParams.FILL_PARENT));
relativeLayout.setBackgroundColor(getResources().getColor(R.color.grayColor));
//CODE FOR ADD MARGINS
RelativeLayout.LayoutParams relativeParams = (RelativeLayout.LayoutParams)relativeLayout.getLayoutParams();
relativeParams.topMargin=80;
relativeLayout.setLayoutParams(relativeParams);
//IMAGE VIEW
ImageView selectedPhoto = new ImageView(this);
selectedPhoto.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
selectedPhoto.setImageResource(R.drawable.ic_launcher);
//TEXT VIEWS
TextView numberCopies = new TextView(this);
numberCopies.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
numberCopies.setGravity(Gravity.CENTER);
numberCopies.setPadding(25, 25, 25, 25);
numberCopies.setTextColor(getResources().getColor(R.color.blackColor));
numberCopies.setText("2 copies ");
RelativeLayout.LayoutParams layoutParamsNumberCopies = …Run Code Online (Sandbox Code Playgroud) 使用XML文件很简单,因为我可以将参数指定为
<android:layout_width="fill_parent" android:layout_height="wrap_content">
Run Code Online (Sandbox Code Playgroud)
但我在通过代码指定它时感到困惑.对于每个视图,我使用指定参数
view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT));
Run Code Online (Sandbox Code Playgroud)
我看到我可以选择将其指定为相对布局,框架布局等.截至目前,我正在为所有视图使用线性布局,例如图像,文本和gridview.是否应根据父元素的布局定义视图参数?或者将它指定为线性布局是否可以,即使视图是例如framelayout的子节点?对不起,但我找不到差异.