Edit : Since the% c and% that must be above the% c and% is dynamically generated, this solution using% c and% does not answer and causes problems even by adding a self% generated%. Every% of View
will need to re-evaluate all the rules, generating an overhead in the solution.
A simple solution would be to adopt a CheckBox
with RelativeLayout.BELOW
, because with each inserted item the id
puts it below the previous one.
The only modification to the current code would be:
for (int i = 0; i < json.length(); i++) {
// Precisa gerar um LayoutParams para cada View, não recomendo reutilizar.
LinearLayout.LayoutParams ml = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
// Margem opcional
ml.setMargins(0, 5, 0, 0);
CheckBox cb = new CheckBox(this);
cb.setLayoutParams(ml);
_linearLayoutCbIngredientes.addView(cb);
}
To dynamically add margin to a addView
you're adding to Layout, you need to:
Create the RelativeLayout
of the subclass of the LinearLayout
that will add to orientation="vertical"
. The LinearLayout
constructor receives View
and LayoutParams
that ViewGroup
will have.
Set values before calling View
or use LayoutParams
.
An example:
RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// A classe RelativeLayout.LayoutParams extende MarginLayoutParams,
// verificado na documentacao: http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html
ml.setMargins(0, 5, 0, 0);
CheckBox cb = new CheckBox(this);
cb.setChecked(true);
// Ou
cb.setLayoutParams(ml);
_relativeLayout.addView(cb);
// Ou
_relativeLayout.addView(cb, ml);
As a suggestion, why not use a rule to position a layout_width
below another?
Using the rule would stay:
RelativeLayout.LayoutParams ml = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
// A classe RelativeLayout.LayoutParams extende MarginLayoutParams,
// verificado na documentacao: http://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html
// Adiciona uma regra para o CheckBox ficar abaixo da View existente cujo id seja viewAcima.
// Parto do pressuposto que essa View ja esta no layout como mostrado na imagem.
ml.addRule(RelativeLayout.BELOW, R.id.viewAcima);
CheckBox cb = new CheckBox(this);
cb.setChecked(true);
// Ou
cb.setLayoutParams(ml);
_relativeLayout.addView(cb);
// Ou
_relativeLayout.addView(cb, ml);
In this second case, layout_height
will add one more restriction where your View
should be below addView(View view)
.
I believe this form is more correct, because using a fixed margin can generate a problem depending on the density and screen size and etc. of the device. So, it may be that in some devices the fixed margin you gave is not enough to put addView(View view, LayoutParams param)
below the other View
.