Cómo agregar múltiples TextView dynamicall a la definición LinearLayout en main.xml
Sé que es posible agregar algunos diseños como Button
y TextView
a un LinearLayout
. Quiero crear más de un TextView
basado en la condición de un bucle for.
Lo he intentado con mi propio camino, pero no soy capaz de crearlo. ¿Alguien sabe cómo crearlo?
- RadioButtons programáticamente agregados se niegan a obedecer la ponderación LayoutParams
- Cómo obtener todas las aplicaciones instaladas en el teléfono Android
- Google Map se está cargando con parches cuadrados
- Diseño de widget Android - fondo negro predeterminado
- ¿Por dónde empezar para el efecto Flip de página en android?
El bucle for será diferente según la condición. Por favor, ayúdame sobre esto. ¿Es posible crear la matriz de TextView
?
Ya he configurado el diseño con
setContentView(R.layout.result_page);
Estoy utilizando Función para agregar esa vista a mi vista existente:
La función es:
public void addAll() { LinearLayout layout = (LinearLayout)findViewById(R.id.myLayout); layout.setOrientation(1); TextView name[] = null; TextView website[] = null; TextView category[] = null; for (int i = 0; i < 5; i++) { name[i] = new TextView(this); name[i].setText("Name = Shreyash"); website[i] = new TextView(this); website[i].setText("Website = shreyah.co.cc"); category[i] = new TextView(this); category[i].setText("Website Category = OWN"); layout.addView(name[i]); layout.addView(website[i]); layout.addView(category[i]); } }
Pero después de eso si ejecuto la aplicación, me muestra error como:
09-08 11:03:28.755: ERROR/AndroidRuntime(318): FATAL EXCEPTION: main 09-08 11:03:28.755: ERROR/AndroidRuntime(318): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.quiz.spellingquiz/com.quiz.spellingquiz.ResultDisplayPage}: java.lang.NullPointerException 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread.access$2300(ActivityThread.java:125) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.os.Handler.dispatchMessage(Handler.java:99) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.os.Looper.loop(Looper.java:123) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread.main(ActivityThread.java:4627) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at java.lang.reflect.Method.invokeNative(Native Method) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at java.lang.reflect.Method.invoke(Method.java:521) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at dalvik.system.NativeStart.main(Native Method) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): Caused by: java.lang.NullPointerException 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at com.quiz.spellingquiz.ResultDisplayPage.addAll(ResultDisplayPage.java:59) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at com.quiz.spellingquiz.ResultDisplayPage.onCreate(ResultDisplayPage.java:34) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627) 09-08 11:03:28.755: ERROR/AndroidRuntime(318): ... 11 more
No sé dónde me equivoco.
Por favor ayúdame sobre esto.
Tengo el resultado con el código de DeeV como este:
Pero quiero establecer la palabra bajo la palabra de la etiqueta, y la respuesta debajo de la respuesta de la etiqueta. Pero, ¿cómo es posible? Creo que tengo que establecer otro LinearLayout para eso. ¿Puede anybudy decirme cómo establecí otro LinearLayout para ese tipo de apariencia?
- Cómo cambiar android spinner popupBackground
- Android EditarTexto Fondo transparente
- Drop-menu en ListView para Android
- Intención de envío dentro de otra Intención
- Android.database.sqlite.SQLiteCursor@435b9ba0
- Cómo configurar el enfoque a la derecha del texto en EditText para android?
- ¿Cómo definir el fondo del botón en un lugar y se utiliza alrededor de toda la aplicación?
- ¿Cómo puedo utilizar la fuente bangla como un valor de cadena en android
Sólo necesita crear una matriz si necesita cambiar las TextViews
más adelante. Sin embargo, si necesita hacer una matriz, algo como esto debería funcionar.
List<TextView> textList = new ArrayList<TextView>(NUM_OF_TEXTS); for(int i = 0; i < NUM_OF_TEXTS; i++) { TextView newTV = new TextView(context); newTV.setText("New message."); newTV.setTextColor(0xFFFF0000); /**** Any other text view setup code ****/ myLinearLayout.addView(newTV); textList.add(newTV); }
Si el texto es estático una vez creado, entonces simplemente puede quitar cualquier referencia a la lista en código, y todavía se agregará a LinearLayout
.
EDITAR:
Asumiendo que entiendo bien su pregunta, usted quiere que el diseño sea algo como esto:
Word: Big Answer: 42 Word: Small Answer: Tough Word: Example Answer: Another Answer
En ese caso, literalmente no tiene que hacer mucho. LinearLayout
pondrá todo en el orden en que lo coloque con addView
. Para actualizar mi código anterior, esto debería funcionar:
List<TextView> wordList = new ArrayList<TextView>(NUM_OF_WORDS); List<TextView> answerList = new ArrayList<TextView>(NUM_OF_ANSWERS); for(int i = 0; i < NUM_OF_WORDS; i++){ TextView blankText = new TextView(context); TextView wordText = new TextView(context); TextView answerText = new TextView(context); blankText.setText(" "); wordText.setText("Word:"); answerText.setText("Answer:"); TextView newWord = new TextView(context); newWord.setText(**** some method of getting the word ****); TextView newAnswer = new TextView(context); newAnswer.setText(**** some method of getting the answer ****); /**** Any other text view setup code ****/ myLinearLayout.addView(wordText); myLinearLayout.addView(newWord); myLinearLayout.addView(answerText); myLinearLayout.addView(newAnswer); myLinearLayout.addView(blankText); wordList.add(newWord); answerList.add(newAnswer); }
LinearLayout lila = new LinearLayout(this); ArrayList<Button> alb = new ArrayList<Button>(); int nButton = 10; for (int i = 0; i < nButton; i++) { alb.add(new Button(this)); lila.addView(alb.get(i)); } //works the same way with TextView alb.get(5).setText("myButton");
Tal vez esto podría ayudar.
EDIT: Lo siento estrictamente lo mismo que DeeV.
- Configuración de android: windowBackground a @ null hace desplazamiento a mancha?
- Android sólo juego en OpenGL: rendimiento en C ++ (NDK) vs Java (Dalvik)