studio linearlayout gridlayout elementos ejemplo dinamico crear amontonados android android-layout android-view android-relativelayout

android - linearlayout - ¿Cómo diseñar vistas en RelativeLayout programáticamente?



linearlayout android ejemplo (9)

Acabo de pasar 4 horas con este problema. Finalmente se dio cuenta de que no debe usar cero como ID de vista . Usted pensaría que está permitido como NO_ID == -1, pero las cosas tienden a fallar si se lo dan a su vista ...

Estoy tratando de lograr lo siguiente mediante programación (en lugar de declarativamente a través de XML):

<RelativeLayout...> <TextView ... android:id="@+id/label1" /> <TextView ... android:id="@+id/label2" android:layout_below: "@id/label1" /> </RelativeLayout>

En otras palabras, ¿cómo puedo hacer que el segundo TextView aparezca debajo del primero, pero quiero hacerlo en código:

RelativeLayout layout = new RelativeLayout(this); TextView label1 = new TextView(this); TextView label2 = new TextView(this); ... layout.addView(label1); layout.addView(label2); setContentView(layout);

Actualizar:

Gracias, TreeUK. Entiendo la dirección general, pero todavía no funciona, "B" se superpone a "A". ¿Qué estoy haciendo mal?

RelativeLayout layout = new RelativeLayout(this); TextView tv1 = new TextView(this); tv1.setText("A"); TextView tv2 = new TextView(this); tv2.setText("B"); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.FILL_PARENT); lp.addRule(RelativeLayout.RIGHT_OF, tv1.getId()); layout.addView(tv1); layout.addView(tv2, lp);


Corta el cuento largo: con un diseño relativo coloca los elementos dentro del diseño.

  1. crear un nuevo RelativeLayout.LayoutParams

    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(...)

    (lo que sea ... rellene el contenido principal o el recuadro, los números absolutos si es necesario o haga referencia a un recurso XML)

  2. Agregar reglas: las reglas se refieren al padre oa otros "hermanos" en la jerarquía.

    lp.addRule(RelativeLayout.BELOW, someOtherView.getId()) lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT)

  3. Solo aplique los parámetros de diseño: la forma más "saludable" de hacerlo es:

    parentLayout.addView(myView, lp)

Cuidado : no cambie el diseño de las devoluciones de llamada de diseño. Es tentador hacerlo porque es cuando las vistas obtienen su tamaño real. Sin embargo, en ese caso, se esperan resultados inesperados.


Este enfoque con ViewGroup.MarginLayoutParams funcionó para mí:

RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.my_layout); TextView someTextView = ... int leftMargin = Util.getXPos(); int topMargin = Util.getYPos(); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( new ViewGroup.MarginLayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); lp.setMargins(leftMargin, topMargin, 0, 0); myLayout.addView(someTextView, lp);


Por lo que he podido juntar, debes agregar la vista usando LayoutParams.

LinearLayout linearLayout = new LinearLayout(this); RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP); parentView.addView(linearLayout, relativeParams);

Todo el crédito que se necesita para establecer una posición relativa en sus elementos programáticamente tiene que asignarles identificadores.

TextView tv1 = new TextView(this); tv1.setId(1); TextView tv2 = new TextView(this); tv2.setId(2);

Luego addRule(RelativeLayout.RIGHT_OF, tv1.getId());


Si realmente desea diseñar manualmente, sugeriría que no use un diseño estándar. Hazlo todo por tu cuenta, aquí un ejemplo de Kotlin:

class ProgrammaticalLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) { private val firstTextView = TextView(context).apply { test = "First Text" } private val secondTextView = TextView(context).apply { text = "Second Text" } init { addView(firstTextView) addView(secondTextView) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { // center the views verticaly and horizontaly val firstTextLeft = (measuredWidth - firstTextView.measuredWidth) / 2 val firstTextTop = (measuredHeight - (firstTextView.measuredHeight + secondTextView.measuredHeight)) / 2 firstTextView.layout(firstTextLeft,firstTextTop, firstTextLeft + firstTextView.measuredWidth,firstTextTop + firstTextView.measuredHeight) val secondTextLeft = (measuredWidth - secondTextView.measuredWidth) / 2 val secondTextTop = firstTextView.bottom secondTextView.layout(secondTextLeft,secondTextTop, secondTextLeft + secondTextView.measuredWidth,secondTextTop + secondTextView.measuredHeight) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // just assume we`re getting measured exactly by the parent val measuredWidth = MeasureSpec.getSize(widthMeasureSpec) val measuredHeight = MeasureSpec.getSize(heightMeasureSpec) firstTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) secondTextView.measures(MeasureSpec.makeMeasureSpec(meeasuredWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) setMeasuredDimension(measuredWidth, measuredHeight) } }

Esto podría darle una idea de cómo podría funcionar esto.


Tratar:

EditText edt = (EditText) findViewById(R.id.YourEditText); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams ( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ); lp.setMargins(25, 0, 0, 0); // move 25 px to right (increase left margin) edt.setLayoutParams(lp); // lp.setMargins(left, top, right, bottom);


llamada

tv1.setId(1)

después

tv1.setText("A");


Ejemplo ejecutable mínimo de Android 22

Fuente:

import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import android.widget.TextView; public class Main extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final RelativeLayout relativeLayout = new RelativeLayout(this); final TextView tv1; tv1 = new TextView(this); tv1.setText("tv1"); // Setting an ID is mandatory. tv1.setId(View.generateViewId()); relativeLayout.addView(tv1); // tv2. final TextView tv2; tv2 = new TextView(this); tv2.setText("tv2"); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.FILL_PARENT); lp.addRule(RelativeLayout.BELOW, tv1.getId()); relativeLayout.addView(tv2, lp); // tv3. final TextView tv3; tv3 = new TextView(this); tv3.setText("tv3"); RelativeLayout.LayoutParams lp2 = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ); lp2.addRule(RelativeLayout.BELOW, tv2.getId()); relativeLayout.addView(tv3, lp2); this.setContentView(relativeLayout); } }

Funciona con el proyecto predeterminado generado por android create project ... Repositorio GitHub con código de compilación mínima .


public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.activity_main); final RelativeLayout relativeLayout = new RelativeLayout(this); final TextView tv1 = new TextView(this); tv1.setText("tv1 is here"); // Setting an ID is mandatory. tv1.setId(View.generateViewId()); relativeLayout.addView(tv1); final TextView tv2 = new TextView(this); tv2.setText("tv2 is here"); // We are defining layout params for tv2 which will be added to its parent relativelayout. // The type of the LayoutParams depends on the parent type. RelativeLayout.LayoutParams tv2LayoutParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); //Also, we want tv2 to appear below tv1, so we are adding rule to tv2LayoutParams. tv2LayoutParams.addRule(RelativeLayout.BELOW, tv1.getId()); //Now, adding the child view tv2 to relativelayout, and setting tv2LayoutParams to be set on view tv2. relativeLayout.addView(tv2); tv2.setLayoutParams(tv2LayoutParams); //Or we can combined the above two steps in one line of code //relativeLayout.addView(tv2, tv2LayoutParams); this.setContentView(relativeLayout); } }