Tengo un diseño para una vista –
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:orientation="vertical">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_header"
style="@style/Home.ListHeader" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_none"
android:visibility="gone"
style="@style/TextBlock"
android:paddingLeft="6px" />
<ListView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/items_list" />
</LinearLayout>
Lo que quiero hacer es mi actividad principal con un diseño como este
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="0px"
android:id="@+id/item_wrapper">
</LinearLayout>
Quiero recorrer mi modelo de datos e inyectar múltiples vistas que consisten en el primer diseño en el diseño principal. Sé que puedo hacer esto creando los controles completamente dentro del código, pero me preguntaba si había una forma de crear dinámicamente las vistas para poder seguir usando un diseño en lugar de poner todo en código.

marca pescador
Utilizar el LayoutInflater
para crear una vista basada en su plantilla de diseño y luego inyectarla en la vista donde la necesite.
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.your_layout, null);
// fill in any details dynamically here
TextView textView = (TextView) v.findViewById(R.id.a_text_view);
textView.setText("your text");
// insert into main view
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.insert_point);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
Es posible que deba ajustar el índice donde desea insertar la vista.
Además, configure LayoutParams de acuerdo con cómo le gustaría que se ajuste a la vista principal. por ejemplo, con FILL_PARENT
o MATCH_PARENT
etc

gabriel negut
Ver el LayoutInflater
clase.
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

Aleadam
Parece que lo que realmente quiere es un ListView con un adaptador personalizado para inflar el diseño especificado. Usando un ArrayAdapter y el metodo notifyDataSetChanged()
usted tiene el control total de la generación y representación de Vistas.
Echa un vistazo a estos tutoriales
Para que la respuesta de @Mark Fisher sea más clara, la vista insertada que se infla debe ser un archivo xml en la carpeta de diseño pero sin un diseño (ViewGroup) como LinearLayout, etc. dentro. mi ejemplo:
res/layout/mi_vista.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/i_am_id"
android:text="my name"
android:textSize="17sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
Luego, el punto de inserción debe ser un diseño como LinearLayout:
res/layout/actividad_principal.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/aaa"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="@+id/insert_point"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</RelativeLayout>
Entonces el código debe ser
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_cart);
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.my_view, null);
ViewGroup main = (ViewGroup) findViewById(R.id.insert_point);
main.addView(view, 0);
}
La razón por la que publico esta respuesta muy similar es que cuando traté de implementar la solución de Mark, me quedé atascado en qué archivo xml debo usar para insert_point y la vista secundaria. En primer lugar, utilicé el diseño en la vista infantil y no funcionaba en absoluto, lo que me llevó varias horas descubrir. Así que espero que mi exploración pueda ahorrar el tiempo de otros.

Tiananhvn
// Parent layout
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.layout);
// Layout inflater
LayoutInflater layoutInflater = getLayoutInflater();
View view;
for (int i = 1; i < 101; i++){
// Add the text layout to the parent layout
view = layoutInflater.inflate(R.layout.text_layout, parentLayout, false);
// In order to get the view we have to use the new view with text_layout in it
TextView textView = (TextView)view.findViewById(R.id.text);
textView.setText("Row " + i);
// Add the text view to the parent layout
parentLayout.addView(textView);
}
Puede verificar la respuesta para este stackoverflow.com/questions/3995215/…
– Dime cómo
18 de abril de 2017 a las 6:45