I’ve been trying to create a custom view that is to be used to indicate the battery level of a proprietary device.
So when the battery level of the device is read the method setPercentage(int batteryLevel) is called on the custom view :
The problem is that regardless of what value I set nothing seems to change in the custom view.
Here is the class :
public class RectangleView extends LinearLayout {
private ArrayList<ImageView> views = new ArrayList<ImageView>();
public RectangleView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init(context);
}
public RectangleView(Context context) {
super(context);
init(context);
}
private void init(Context context) {
this.setOrientation(LinearLayout.HORIZONTAL);
for (int i = 0; i < 10; i++) {
ImageView loadingPiece = new ImageView(context);
loadingPiece.setBackgroundColor(Color.BLACK);
this.addView(loadingPiece);
LayoutParams layoutParams = (LayoutParams)loadingPiece.getLayoutParams();
layoutParams.weight = 1.0f;
layoutParams.height = this.getHeight();
layoutParams.width = 0;
loadingPiece.setLayoutParams(layoutParams);
views.add(loadingPiece);
}
}
public void setPercentage(int amountToShow) {
for (int i = 0; i < views.size(); i++)
if (i < amountToShow)
views.get(i).setVisibility(View.VISIBLE);
else
views.get(i).setVisibility(View.INVISIBLE);
}
}
Caling setPersentage(5) should show 5 imageviews – However nothing is changed and the view itself seems empty.
I think that happens because of the
LayoutParamsyou used(getHeight()returning0at that moment). See if this makes a difference: