¿Cómo puedo añadir un TextView a un LinearLayout dinámicamente en Android?
Intento agregar un TextView a un LinearLayout dinámicamente tal como en el código siguiente, pero no aparece cuando corro la aplicación?
setContentView(R.layout.advanced); m_vwJokeLayout=(LinearLayout) this.findViewById(R.id.m_vwJokeLayout); m_vwJokeEditText=(EditText) this.findViewById(R.id.m_vwJokeEditText); m_vwJokeButton=(Button) this.findViewById(R.id.m_vwJokeButton); TextView tv=new TextView(this); tv.setText("test"); this.m_vwJokeLayout.addView(tv);
¿Cuál es el problema?
- Compruebe si la vista de texto está elipsada en android
- No se puede inflar correctamente el diseño de un fragmento en la aplicación de Android
- Establecer una cadena spannable no funciona en una simple Textview
- Cómo dibujar correctamente texto en una clase extendida para TextView?
- Cómo dar formato al texto en la cadena que se muestra en TextView
- Cómo obtener marcas de acento en las letras de un TextView Android
- Conversión de TextView a String (tipo de) Android
- Expanda TextView con wrap_content hasta que la vista de vecino llegue al final del padre
- Cómo cambiar TextView texto en DataChange sin llamada atrás TextWatcher Listener
- ¿Cómo detectar pulsaciones de teclas de caracteres?
- Temporizador de TextView de Android
- Haga que el contenido de textview contenga texto en negrita y regular
- TextView "fill_parent" no rellena el padre
LayoutParams lparams = new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); TextView tv=new TextView(this); tv.setLayoutParams(lparams); tv.setText("test"); this.m_vwJokeLayout.addView(tv);
Usted puede cambiar lparams según sus necesidades
Aquí hay una respuesta más general para los futuros espectadores de esta pregunta. El diseño que vamos a hacer es a continuación:
Método 1: Agregar TextView a LinearLayout existente
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dynamic_linearlayout); LinearLayout linearLayout = (LinearLayout) findViewById(R.id.ll_example); // Add textview 1 TextView textView1 = new TextView(this); textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); textView1.setText("programmatically created TextView1"); textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB textView1.setPadding(20, 20, 20, 20);// in pixels (left, top, right, bottom) linearLayout.addView(textView1); // Add textview 2 TextView textView2 = new TextView(this); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.RIGHT; layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom) textView2.setLayoutParams(layoutParams); textView2.setText("programmatically created TextView2"); textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB linearLayout.addView(textView2); }
Tenga en cuenta que para LayoutParams
debe especificar el tipo de diseño para la importación, como en
import android.widget.LinearLayout.LayoutParams;
De lo contrario, deberá utilizar LinearLayout.LayoutParams
en el código.
Aquí está el xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ll_example" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff99ccff" android:orientation="vertical" > </LinearLayout>
Método 2: Crear LinearLayout y TextView programaticamente
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // NOTE: setContentView is below, not here // Create new LinearLayout LinearLayout linearLayout = new LinearLayout(this); linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setBackgroundColor(0xff99ccff); // Add textviews TextView textView1 = new TextView(this); textView1.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); textView1.setText("programmatically created TextView1"); textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB textView1.setPadding(20, 20, 20, 20); // in pixels (left, top, right, bottom) linearLayout.addView(textView1); TextView textView2 = new TextView(this); LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.gravity = Gravity.RIGHT; layoutParams.setMargins(10, 10, 10, 10); // (left, top, right, bottom) textView2.setLayoutParams(layoutParams); textView2.setText("programmatically created TextView2"); textView2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18); textView2.setBackgroundColor(0xffffdbdb); // hex color 0xAARRGGBB linearLayout.addView(textView2); // Set context view setContentView(linearLayout); }
Método 3: Agregar un diseño xml a otro diseño xml de forma programática
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.dynamic_linearlayout); LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.dynamic_linearlayout_item, null); FrameLayout container = (FrameLayout) findViewById(R.id.flContainer); container.addView(view); }
Aquí está dynamic_linearlayout.xml:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/flContainer" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
Y aquí está el dynamic_linearlayout_item.xml para agregar:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/ll_example" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff99ccff" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff66ff66" android:padding="20px" android:text="programmatically created TextView1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ffffdbdb" android:layout_gravity="right" android:layout_margin="10px" android:textSize="18sp" android:text="programmatically created TextView2" /> </LinearLayout>
He personalizado más código @Suragch. Mi salida se ve
Escribí un método para detener la redundancia de código.
TextView createATextView(int layout_widh, int layout_height, int align, String text, int fontSize, int margin, int padding) { TextView textView_item_name = new TextView(this); // LayoutParams layoutParams = new LayoutParams( // LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); // layoutParams.gravity = Gravity.LEFT; RelativeLayout.LayoutParams _params = new RelativeLayout.LayoutParams( layout_widh, layout_height); _params.setMargins(margin, margin, margin, margin); _params.addRule(align); textView_item_name.setLayoutParams(_params); textView_item_name.setText(text); textView_item_name.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize); textView_item_name.setTextColor(Color.parseColor("#000000")); // textView1.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB textView_item_name.setPadding(padding, padding, padding, padding); return textView_item_name; }
Puede llamarse como
createATextView(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT, subTotal.toString(), 20, 10, 20);
Ahora puede agregar esto a un RelativeLayout dinámicamente. LinearLayout es igual, solo agrega una orientación.
RelativeLayout primary_layout = new RelativeLayout(this); LayoutParams layoutParam = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); primary_layout.setLayoutParams(layoutParam); // FOR LINEAR LAYOUT SET ORIENTATION // primary_layout.setOrientation(LinearLayout.HORIZONTAL); // FOR BACKGROUND COLOR primary_layout.setBackgroundColor(0xff99ccff); primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_LEFT, list[i], 20, 10, 20)); primary_layout.addView(createATextView(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, RelativeLayout.ALIGN_PARENT_RIGHT, subTotal.toString(), 20, 10, 20));
Diseño
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <LinearLayout android:id="@+id/layoutTest" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" > </LinearLayout> </RelativeLayout>
Archivo de clase :
setContentView(R.layout.layout_dynamic); layoutTest=(LinearLayout)findViewById(R.id.layoutTest); TextView textView = new TextView(getApplicationContext()); textView.setText("testDynamic textView"); layoutTest.addView(textView);
TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null); rowTextView.setText(text); layout.addView(rowTextView);
Así es como estoy usando esto:
private List<Tag> tags = new ArrayList<>(); if(tags.isEmpty()){ Gson gson = new Gson(); Type listType = new TypeToken<List<Tag>>() { }.getType(); tags = gson.fromJson(tour.getTagsJSONArray(), listType); } if (flowLayout != null) { if(!tags.isEmpty()) { Log.e(TAG, "setTags: "+ flowLayout.getChildCount() ); flowLayout.removeAllViews(); for (Tag tag : tags) { FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT); lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom); TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null); rowTextView.setText(tag.getLabel()); rowTextView.setLayoutParams(lparams); flowLayout.addView(rowTextView); } } Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() ); }
Y esta es mi etiqueta personalizada llamada TextView:
<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="10dp" android:textAllCaps="true" fontPath="@string/font_light" android:background="@drawable/tag_shape" android:paddingLeft="11dp" android:paddingTop="6dp" android:paddingRight="11dp" android:paddingBottom="6dp">
Este es mi tag_shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <solid android:color="#f2f2f2" /> <corners android:radius="15dp" /> </shape>
Efecto
En otro lugar estoy añadiendo vistas de texto con nombres de idioma desde el diálogo con listview:
Si está utilizando Linearlayout. Sus params deben ser "wrap_content" para agregar datos dinámicos en tu layout xml. Si utiliza coincidencia o relleno padre entonces no puede ver la salida.
Debería ser así.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" > </ListView> </LinearLayout>
- Escala la imagen de fondo para ajustar el contenido del diseño
- Cómo escribir estilo de texto de error de EditText en android?