Reputation: 124
I have multiple buttons that are created dynamically in a for loop and are not having an ID. I need to do automation testing on those buttons. How can I do this with Espresso? This is the for loop that creates the various buttons:
for (int i = 0; i < numberOfSamples; i++) {
TableRow.LayoutParams vl = new TableRow.LayoutParams(30,30);
Button b = new Button(context);
b.setId(((blockNumber * 10000)+i));
//b.setHint(i);
//b.setHint(blockNumber);
// double selectedGrade = 0;
// if(FinalSurvey.multi[blockNumber][i] != 0){
// selectedGrade = FinalSurvey.multi[blockNumber][i];
// }
// final int makeHighlight = selectedGrade;
b.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.a));
b.setAlpha(1.0f);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ViewsAdding va = new ViewsAdding();
va.showGrades(context, v, grades);
view = v;
maincontext = context;
}
});
if(i%5 == 0){
innerLayout = new LinearLayout(context);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
innerLayout.setLayoutParams(innerparams);
vl.setMargins(5, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else if (i%5 ==1) {
vl.setMargins(22, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else if (i%5 ==2) {
vl.setMargins(25, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
mainLinearLayout.addView(innerLayout);
b = null;
}else if (i%5 ==3) {
innerLayout = new LinearLayout(context);
innerLayout.setOrientation(LinearLayout.HORIZONTAL);
innerLayout.setLayoutParams(innerparams);
vl.setMargins(35, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
if(i == numberOfSamples-1){
mainLinearLayout.addView(innerLayout);
}
b = null;
}else{
vl.setMargins(30, 5, 5, 5);
b.setLayoutParams(vl);
innerLayout.addView(b);
mainLinearLayout.addView(innerLayout);
b = null;
}
}
return mainLinearLayout;
}
Upvotes: 3
Views: 1883
Reputation: 3819
In your code where you create the buttons add a tag to the button depending on the case:
button.setTag("someTag");
so in your case you could do it in your if clauses:
if(i%5 == 0){
...
b.setTag("case0-" + i);
...
}else if (i%5 ==1) {
...
b.setTag("case1-" + i);
...
}
...
and then in your test you can get the buttons with this or click it:
onView(allOf(withTagValue(is((Object) "case0-0")), isDisplayed())).perform(click());
onView(allOf(withTagValue(is((Object) "case0-0")), isDisplayed())).perform(click());
you can also replace the "case0-0" string with a loop to regenerate the tags
Upvotes: 6