Cómo establecer la posición de la vista mientras se utiliza addView
Estoy agregando varias View
s por código en Layout
. Necesito que cada nueva View
esté por encima de la anterior (arriba del diseño de los padres).
EDIT: Para ser más preciso describiré lo que el módulo de la aplicación debe hacer. El usuario comienza con una pantalla limpia y un botón en la parte inferior de la pantalla. El botón agrega una View
en la parte superior de la pantalla. Los siguientes clics deben agregar vistas siguientes por encima de las anteriores para que la View
más reciente esté en la parte superior de un contenedor. La aplicación guarda el estado y al reiniciar el usuario ve las vistas en el mismo orden.
- Diferencia entre vista y subvista - Android
- Cómo hacer aplicaciones hermosas y con estilo como Timely
- ¿Cómo implementar la vista de pila personalizada en android?
- ¿Cuántos WindowInsets hay?
- Dibujando una vista y todos sus hijos
- Cómo agregar rectángulos encima del rectángulo existente en el lienzo
- Posiciona MediaController dentro de un Fragmento
- Habilitar longClick en WebView
- OnSaveInstanceState () y onRestoreInstanceState (estado parcelable) no se llaman?
- Cambiar usuario o volver a autenticar con Instagram
- Ocultar pestañas ViewPager al desplazarse hacia arriba.
- Android - Javascript: cómo ejecutar jquery en webview
- Cómo inflar varias instancias de un diseño con el mismo id dentro de un diseño inflado
Llame al siguiente método del evento onClick de Button .
private final int LAYOUT_TOP_INDEX = 0; private void addViewOnTop(View view){ if(layout != null && view !=null) layout.addView(view, LAYOUT_TOP_INDEX); }
donde 'layout' es su Layout (por ejemplo, LinearLayout) al que se va a agregar la vista.
Realmente necesitaría más información de usted para dar una respuesta más exacta, pero si usted está diciendo lo que pienso que usted es entonces usted puede apenas agregar estas vistas a un LinearLayout con la orientación fijada a vertical.
Y suponiendo que estás iterando a través de una lista para añadir dinámicamente vistas, en lugar de incrementar desde 0, incrementar el tamaño desde la lista.
for(int i = size; i >= 0; i--){ linearLayout.add(new TextView(Context)); }
View
posiciones de ViewGroup
dentro de ViewGroup
s están definidas por LayoutParams
¿Como sucedió esto? Las vistas pasan su LayoutParams a sus padres ViewGroups
//100% programatic approach with simple LayoutParams LinearLayout myLinearLayout = new LinearLayout(this); //if the **parent** of the new linear layout is a FrameLayout FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); //or if you have the XML file you don't have to worry about this //myLinearLayout = (LinearLayout)findViewById(R.id.my_simple_linear_layout); //you could have a LinkedList<TextView> LinkedList<TextView> textViewList = new LinkedList<>(); //assuming the order is the correct order to be displayed Iterator<TextView> descendingIterator = textViewList.descendingIterator(); while(descendingIterator.hasNext()) { //just add each TextView programatically to the ViewGroup TextView tView = descendingIterator.next(); myLinearLayout.addView(tView); }
Al igual que definimos LayoutParams
para el LinearLayout
también podríamos definir LayoutParams para el TextView
IMPORTANTE: al configurar LayoutParams debe asegurarse de que se ajustan al VIEWGROUP, que es el padre de la Vista que se agrega
private TextView textViewFactory(String myText) { TextView tView = new TextView(getBaseContext()); //controling the position relatively to the PARENT //because you are adding the textview to a LINEAR LAYOUT LinearLayout.LayoutParams paramsExample = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f); tView.setLayoutParams(paramsExample); //configuring the insides of the textview //you can also do all kinds of stuff programatically tView.setGravity(Gravity.CENTER_HORIZONTAL); tView.setPadding(10, 10, 10, 10); tView.setTypeface(Typeface.DEFAULT_BOLD);// (null, Typeface.BOLD_ITALIC); tView.setTypeface(Typeface.SANS_SERIF); tView.setTypeface(null, Typeface.ITALIC); tView.setTypeface(Typeface.defaultFromStyle(R.style.AppTheme)); tView.setId(R.id.aux_info); tView.setText(myText); //.........all kinds of stuff really return tView; }
Si quiere decir agregar una vista de forma programática para que la nueva se añada encima de la anterior, en lugar de debajo de ella, entonces sugiero esto:
- Mantener un ArrayList con los elementos que desea convertir en vistas
- Ponerlos en un ListView
- Cuando desea agregar una nueva vista que debe aparecer en la parte superior de la lista, insertarla como el primer elemento de su ArrayList y volver a crear el ListView desde ella.
- Cómo cambiar entre gcc y clang en Android NDK Revision 11?
- Android ListView Ir a la posición del cursor