meta data for this page
Inflater
Exemple pour ajouter un layout xml dans une vue
Voir la vidéo sur YouTube
MainActivity.java
===== MainActivity.java=====
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout lyMain = findViewById(R.id.ly_main); LayoutInflater inflater = getLayoutInflater(); for (int i = 0; i < 30; i++) { View myLayout = inflater.inflate(R.layout.carre, lyMain, false); myLayout.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent)); TextView tv2 = myLayout.findViewById(R.id.textView2); tv2.setText("Texte " + i); lyMain.addView(myLayout); } } }
activity_main.xml
===== activitymain.xml ===== <sxh xml> <?xml version=“1.0” encoding=“utf-8”?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android=“http://schemas.android.com/apk/res/android” xmlns:app=“http://schemas.android.com/apk/res-auto” xmlns:tools=“http://schemas.android.com/tools” android:id=“@+id/lyconst”
android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
<Button android:id="@+id/bt_second" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="button" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<TextView android:id="@+id/tv_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" app:layout_constraintBottom_toTopOf="@+id/bt_second" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" />
<HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/bt_second">
<LinearLayout android:id="@+id/ly_main" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal" /> </HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout> </sxh>
carre.xml
===== carre.xml =====
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginHorizontal="5dp"> <TextView android:id="@+id/textView2" android:layout_width="100dp" android:layout_height="100dp" android:layout_marginHorizontal="5dp" android:backgroundTint="#3A79D8" android:foregroundGravity="center" android:gravity="center" android:text="TextView" android:textAlignment="gravity" /> </RelativeLayout>