I have a class to which I need to add one or more Views. In this example, a single ImageView.
I can add views without a problem and align them using LayoutParameters, but when I try to align or center them somewhere along the vertical axis, they either stick to the top or don’t appear at all (they are likely just out of view).
In the constructor I call a method fillView(), which happens after all dimensions and such are set.
fillView()
public void fillView(){
img = new ImageView(context);
rl = new RelativeLayout(context);
img.setImageResource(R.drawable.device_access_not_secure);
rl.addView(img, setCenter());
this.addView(rl, matchParent());
}
matchParent()
public LayoutParams matchParent(){
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
lp.setMargins(0, 0, 0, 0);
return lp;
}
setCenter()
public LayoutParams setCenter(){
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE); //This puts the view horizontally at the center, but vertically at the top
return lp;
}
Similarly, adding rules such as ALIGN_RIGHT or BELOW will work fine, but ALIGN_BOTTOM or CENTER_VERTICALLY will not.
I tried using both this method and the setGravity() a LinearLayout offers, with the same results.
While I still don’t know why my method worked horizontally, but not vertically, I did solve the problem. The posted methods worked, the problem was hidden in
onMeasure().I previously set the dimensions by simply passing them to
setMeasuredDimension(). I fixed the issue by also passing them to thelayoutParams(). I also changed the integers I used toMeasureSpecswhile I was at it.I changed this:
to this:
getT_Width()andgetT_Heigth()are methods I used to get some custom dimensions I set elsewhere.I hope this helps somebody.