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

handling programatically created layout from xml: ids challenge

我需要能够以编程方式多次从 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 下方.

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

如果你指导我解决问题,我将不胜感激。

如果您不需要视图的 id 用于其他目的,您可以更简单地解决。

如果我明白你想做什么,你需要的是垂直 LinearyLayout 而不是 RelativeLayout,然后子视图将在彼此下面添加一个

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

  • 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);

希望它能让您了解如何实用地对齐视图。