Reputation: 252
I have a vertical LinearLayout, which I want to fill with horizontal LinearLayouts (which act like rows). Each of these should effectively be identical, except several items within them use a number, which should increase each time.
For example:
<LinearLayout android:id="@+id/row1" >
<SeekBar
android:id="@+id/seekBar"
android:tag="1"
/>
</LinearLayout>
<LinearLayout android:id="@+id/row2" >
<SeekBar
android:id="@+id/seekBar"
android:tag="2"
/>
</LinearLayout>
<LinearLayout android:id="@+id/row3" >
<SeekBar
android:id="@+id/seekBar"
android:tag="3"
/>
</LinearLayout>
In JavaScript, I might use something like this to 'automate' their creation:
for (var i = 0; i < count; i++) {
child = document.createElement("div");
child.id = "row" + i;
parent.appendChild(child);
}
Is there a way to 'automate' the creation of these, such that I can just have a single 'model' of one, then iterate over it several times, 'passing in' the number each time? I can use a Java-based or XML-based solution.
I've tried using for each one, which solved part of the problem, but couldn't find an effective way to 'pass in' a different number each time. (The numbers are to identify the inputs within the rows from Java - if there's a better way to manage this, that could also be helpful).
Upvotes: 0
Views: 187
Reputation: 239
You can build Layout by Java code in the Activity - onCreate
You can dynamic modify of layout
For example: Build 3 seekbars and delete the first seekbar by id.
public class MainActivity extends AppCompatActivity {
ArrayList<Integer> seekbarsID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
seekbarsID = new ArrayList<>();
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
for (int i = 1; i < 4; i++) {
SeekBar seekbar = new SeekBar(this);
int id;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
id = View.generateViewId();
}else{
id = 99999999+i;
}
seekbar.setId(id);
seekbarsID.add (id);
seekbar.setTag(i);
layout.addView(seekbar);
}
setContentView(layout);
layout.removeView(findViewById(seekbarsID.get(0)));
}
}
Upvotes: 1