Search code examples
androidxmlandroid-layoutandroid-fragmentsonactivityresult

handling programatically created layout from xml: ids challenge


I need to be able to add a layout to my main layout from xml file many times programatically.

The problem is handling assigning ids of the new layout's views. See the code:

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

I don't know where the problem is, so here is how the app works now: I add a new layout, it gets positioned correctly below layout_header.

But when I add the second or more layouts they overlap each other on top of the app instead of being positioned one below the other.

I'd appreciate if you guided me to the solution of the problem.


Solution

  • If you don't need views'ids for other purposes you could solve more simple.

    If I've understood what you are trying to do, what you need is a vertical LinearyLayout instead of a RelativeLayout, then subviews will be added one below each other