Cree un nuevo TextView mediante programación y luego muéstrelo debajo de otro TextView

String[] textArray={"one","two","asdasasdf asdf dsdaa"}; int length=textArray.length; RelativeLayout layout = new RelativeLayout(this); RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); for(int i=0;i<length;i++){ TextView tv=new TextView(getApplicationContext()); tv.setText(textArray[i]); relativeParams.addRule(RelativeLayout.BELOW, tv.getId()); layout.addView(tv, relativeParams); } 

Necesito hacer algo así … así que se mostraría como

 one two asdfasdfsomething 

en la pantalla..

Si no es importante usar un RelativeLayout, puede usar LinearLayout y hacer esto:

 LinearLayout linearLayout = new LinearLayout(this); linearLayout.setOrientation(LinearLayout.VERTICAL); 

Hacer esto le permite evitar el método addRule que ha intentado. Simplemente puede utilizar addView () para agregar nuevas TextViews.

Código completo:

 String[] textArray = {"One", "Two", "Three", "Four"}; LinearLayout linearLayout = new LinearLayout(this); setContentView(linearLayout); linearLayout.setOrientation(LinearLayout.VERTICAL); for( int i = 0; i < textArray.length; i++ ) { TextView textView = new TextView(this); textView.setText(textArray[i]); linearLayout.addView(textView); } 
 public View recentView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Create a relative layout and add a button relativeLayout = new RelativeLayout(this); btn = new Button(this); btn.setId((int)System.currentTimeMillis()); recentView = btn; btn.setText("Click me"); relativeLayout.addView(btn); setContentView(relativeLayout); btn.setOnClickListener(new View.OnClickListener() { @Overr ide public void onClick(View view) { //Create a textView, set a random ID and position it below the most recently added view textView = new TextView(ActivityName.this); textView.setId((int)System.currentTimeMillis()); layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); layoutParams.addRule(RelativeLayout.BELOW, recentView.getId()); textView.setText("Time: "+System.currentTimeMillis()); relativeLayout.addView(textView, layoutParams); recentView = textView; } }); } 

Esto se puede modificar para mostrar cada elemento de una matriz String en diferentes TextViews.

Pruebe este código:

 final String[] str = {"one","two","three","asdfgf"}; final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl); final TextView[] tv = new TextView[10]; for (int i=0; i<str.length; i++) { tv[i] = new TextView(this); RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT); params.leftMargin = 50; params.topMargin = i*50; tv[i].setText(str[i]); tv[i].setTextSize((float) 20); tv[i].setPadding(20, 50, 20, 50); tv[i].setLayoutParams(params); rl.addView(tv[i]); } 

No está asignando ningún identificador a la vista de texto, pero está utilizando tv.getId() para pasarlo al método addRule como parámetro. Trate de establecer un identificador único a través de tv.setId(int) .

También puede utilizar el LinearLayout con orientación vertical, que podría ser más fácil en realidad. Prefiero LinearLayout sobre RelativeLayouts si no es necesario de lo contrario.

  • Android TextView y el botón de lado a lado, ellipsize izquierda TextView
  • Cómo utilizar el centro de una vista como un punto de referencia dentro de un RelativeLayout
  • Las dependencias circulares no pueden existir en RelativeLayout, android?
  • Alinear la casilla de verificación dentro de un diseño relativo
  • CheckBox no aparece en CheckedTextView
  • Cómo establecer la gravedad de textview programatically con RelativeLayout?
  • Mantenga la altura de RelativeLayout tan pequeña como sea posible, pero aumente la altura de los niños para llenar todo el espacio disponible
  • RelativeLayout "No se pudo resolver el recurso ..." Android
  • RelativeLayout refresh after view.setVisibility (View.GONE) y view.setVisibility (View.VISIBLE)
  • ¿Qué pasa con setScaleX / setScaleY?
  • ¿Por qué la gravedad no funciona cuando se aplica al diseño relativo?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.