从xml:ids挑战处理以编程方式创建的布局

时间:2017-09-20 17:34:50

标签: android xml android-layout android-fragments onactivityresult

我需要能够以编程方式多次从xml文件向我的主布局添加布局。

问题是处理分配新布局视图的ID。见代码:

MainFragment.java

private int belowOfWhat = R.id.layout_header;
...

 onActivityResult:

LayoutInflater myInflater = LayoutInflater.from(getContext());
RelativeLayout layout = (RelativeLayout) myInflater.inflate(R.layout.assignment_layout, null, false);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
//here problems start
//i want to position the new layout below the previously created layout
params.addRule(RelativeLayout.BELOW, belowOfWhat);
layout.setLayoutParams(params);
mRelativeLayout = rootView.findViewById(R.id.to_do_layout);
mRelativeLayout.addView(layout);
belowOfWhat = generateViewId();
idsOfToDos.add(belowOfWhat);
CheckBox assignmentCheckbox = (CheckBox) 
//assignment_checkbox is an id of checkbox in the xml layout I add
rootView.findViewById(R.id.assignment_checkbox);
assignmentCheckbox.setId(belowOfWhat);
assignmentCheckbox.setText(mToDoInfo);

我不知道问题出在哪里,所以现在应用程序的工作原理如下:我添加了一个新的布局,它在layout_header 下正确定位

但是当我添加第二个或更多布局时,它们在应用程序顶部相互重叠,而不是一个位于另一个之下。

如果你引导我解决问题,我会很感激。

2 个答案:

答案 0 :(得分:1)

如果您不需要其他目的的观看次数,则可以解决更为简单的问题。

如果我了解您要执行的操作,您需要的是垂直LinearyLayout而不是RelativeLayout,那么子视图将相互添加一个

答案 1 :(得分:0)

您必须使用相对布局并使用以下属性来对齐视图。

  • RelativeLayout.BELOW
  • RelativeLayout.RIGHT_OF
  • RelativeLayout.ALIGN_BOTTOM

RelativeLayout layout = new RelativeLayout(this);     RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);     layout.setLayoutParams(的LayoutParams);

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params3 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

TextView tv1 = new TextView(this);
tv1.setId(1);
tv1.setText("textView1");

TextView tv2 = new TextView(this);
params2.addRule(RelativeLayout.RIGHT_OF, tv1.getId());
tv2.setId(2);
tv2.setText("textView2");

TextView tv3 = new TextView(this);
params3.addRule(RelativeLayout.BELOW, tv1.getId());
tv3.setId(3);
tv3.setText("textView3");

TextView tv4 = new TextView(this);
params4.addRule(RelativeLayout.RIGHT_OF, tv3.getId());
params4.addRule(RelativeLayout.ALIGN_BOTTOM, tv3.getId());
tv4.setId(4);
tv4.setText("textView4");

layout.addView(tv1, params1);
layout.addView(tv2, params2);
layout.addView(tv3, params3);
layout.addView(tv4, params4);

希望如此能让您了解如何以务实的方式对齐视图。