I have about 100 views (Buttons,Textviews and ImageButton) in my activity that i create in a for loop. My app runs slow on older versions of android ( 5 and below) and sometimes it does not even load the views.
My question is, what is the proper way of handling such views and loading them without putting too much load on the main thread?
I couldn't use a separate thread since i cant reference UI elements from any other thread than the main one.
Thanks.
for (int i = 0; i < arr.size(); i++) {
String name = arr.get(i).getName();
final int songPath = arr.get(i).getSongPath();
int iconPath = arr.get(i).getIconPath();
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
relativeLayout.setLayoutParams(rlp);
buttons[i] = new ImageButton(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 350);
params.setMargins(0, 0, 0, 8);
buttons[i].setLayoutParams(params);
buttons[i].setBackgroundResource(iconPath);
buttons[i].setTag(name + "button");
buttons[i].setId(id++);
TextView emoteName = new TextView(this);
RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
textParams.addRule(RelativeLayout.BELOW, buttons[i].getId());
textParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
textParams.setMargins(20,10,0,0);
emoteName.setText(name.toUpperCase());
emoteName.setId(id++);
emoteName.setTextSize(20f);
emoteName.setLayoutParams(textParams);
Button threedots = new Button(this);
RelativeLayout.LayoutParams threedotsParams = new RelativeLayout.LayoutParams(50, RelativeLayout.LayoutParams.WRAP_CONTENT);
threedotsParams.addRule(RelativeLayout.BELOW, buttons[i].getId());
threedotsParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
threedotsParams.addRule(RelativeLayout.ALIGN_RIGHT,buttons[i].getId());
threedotsParams.setMargins(0,0,0,0);
threedots.setText(getString(R.string.vertical_ellipsis));
threedots.setTextSize(25f);
threedots.setBackgroundColor(Color.TRANSPARENT);
threedots.setLayoutParams(threedotsParams);
final int counterForOnClick = i;
threedots.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ShowDialog(arr.get(counterForOnClick));
}
});
relativeLayout.addView(buttons[i]);
relativeLayout.addView(emoteName);
relativeLayout.addView(threedots);
if (i % 2 == 0) {
leftLayout.addView(relativeLayout);
} else {
rightLayout.addView(relativeLayout);
}
final int index = i;
buttons[i].setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playEmoteSound(songPath);
}
});
}