I would like to create a method which returns a RelativeLayout
created dynamically. To be clear, let's use this simplified example:
private RelativeLayout createLayout() {
RelativeLayout layout = new RelativeLayout(activity);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(params);
TextView tv1 = new TextView(activity);
tv1.setText("Text 1");
TextView tv2 = new TextView(activity);
tv2.setText("Text 2");
TextView tv3 = new TextView(activity);
tv3.setText("Text 3");
layout.addView(tv1);
layout.addView(tv2);
layout.addView(tv3);
return layout;
}
Now I want to position these TextView
s relatively to each other. For that I have the idea to use a LayoutParams
with the addRule
method.
But this method requires an ID, eg addRule(RelativeLayout.BELOW, tv2Id)
. It means that I have to set an ID for each TextView
s.
My problem is that the createLayout method will be called several times, so the question is:
Do I have to set different IDs for the TextView
s each time the method is called in order to avoid conflicts ? If so, how can I do that ?
Most generally, Is there a better solution for doing it ?
EDIT
The idea behind this is to have a kind of ListView
, where each item contains a Map
(that can be shown or hidden).
Problem: the Map can't be scroll if it is inside a ListView
(at least I did not manage to do that).
For that, I have decided to use a ScrollView
and a LinearLayout
to copy the behaviour of a ListView
. This way the Map
can be scrolled correctly and now, all I have to do is to create the items dynamically
ID's don't have to be unique. As you can see from this extract
setId (int id)
Sets the identifier for this view. The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.
But like you said, if you want to avoid conflict then you have to find a way to generate unique identifiers for each view.
Frankly, IMO I don't think it matters much the value of the ID. You can use 10, 20, 30. Just make sure you can have access to them anytime you need it, possible using a static final
variable.
You asked if there is a better solution, yes there is. The most preferred way is to inflate an xml layout.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.