2010-12-09 9 views
36
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); 
} 

tengo que hacer algo por el estilo .. por lo que sería mostrar comoCrear una nueva programación TextView luego desplegarla por debajo de otro TextView

one 
two 
asdfasdfsomething 

en la pantalla ..

+1

En pocas palabras, lo que está mal con su código? ¿Qué no funciona? Por cierto, si esto es una actividad, simplemente use 'this' en lugar de' getApplicationContext() '. – EboMike

+0

el título de su pregunta dice "mostrarlo _abajo_ otra vista de texto", pero su pregunta establece de manera diferente, con todos los textos en una fila; aclare o formatee el texto de la pregunta en consecuencia. –

+0

La pregunta no estaba formateada correctamente - Lo arreglé. (Probablemente no sea intuitivo que las líneas nuevas se traguen) – EboMike

Respuesta

2

Eres no asigna ningún id. a la vista de texto, pero está usando tv.getId() para pasarlo al método addRule como parámetro. Intente establecer una identificación única a través del tv.setId(int).

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

+0

¿Cómo se puede asignar un id único programáticamente? Me refiero a cómo estar seguro de que será único, cuando nunca conocerás los valores de los identificadores en xml, y los identificadores que aparecerán en –

+0

. Conocerás los valores de los identificadores en xml, ¿por qué no lo harías? Haga ids como 'thisKindofElem001',' thisKindofElem002' etc. – fiatjaf

17
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 de Cadenas en diferentes TextViews.

56

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

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

Hacer esto le permite evitar el método addRule que haya probado. Simplemente puede usar 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); 
} 
+4

Votantes, ¿se preocupan por explicarlo? – WeNeigh

+3

No use el contexto de la aplicación para crear vistas. Usa el contexto de la actividad. – bryn

+0

Gracias. actualizado. – WeNeigh

15

probar 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]); 
} 
+0

¿Cómo puedo definir rl en el archivo activity_main.xml? – gimmegimme