Dynamically loading an XML file in Linringayout

I have 2 xml files:

main.xml

<HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/ll" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal"> </LinearLayout> </HorizontalScrollView> 

items.xml

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rl" android:layout_width="100dp" android:layout_height="100dp"> <ImageView android:id="@+id/img" android:layout_width="50dp" android:layout_height="50dp" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:contentDescription="@string/app_name" android:gravity="center" android:src="@drawable/icon_shop2" /> <TextView android:id="@+id/providerName" style="@style/WhiteTextMedium" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/img" android:layout_gravity="bottom" android:paddingLeft="10dp" android:text="Example" /> </RelativeLayout> 
main is used for MainActivity. My question is how to dynamically load 3 items.xml layouts into a Linringayout in a HorizontalScrollView from main.xml !
+6
source share
2 answers

Try this way, hope it helps you solve your problem.

 LinearLayout ll; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ll = (LinearLayout) findViewById(R.id.ll); for (int i=0;i<3;i++){ View view = LayoutInflater.from(this).inflate(R.layout.items,null); ImageView imageView = view.findViewById(R.id.img); TextView providerName = view.findViewById(R.id.providerName); // Assigning value to imageview and textview here ll.addView(view); } 
+10
source

There are two ways to do this:

Path to the left (using xml, if the number of elements is fixed):

 <HorizontalScrollView android:layout_width="match_parent" android:layout_height="wrap_content" > <LinearLayout android:id="@+id/ll" android:layout_width="wrap_content" android:layout_height="match_parent" android:orientation="horizontal"> <include android:id="@+id/item1" layout="@layout/items.xml"/> <include android:id="@+id/item2" layout="@layout/items.xml"/> <include android:id="@+id/item3" layout="@layout/items.xml"/> </LinearLayout> </HorizontalScrollView> 

Path to the right (in action using the Inflator layout, if the number of elements is dynamic):

 setContentView(R.layout.main); LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout ll = (LinearLayout) findViewById(R.id.ll); View v = inflater.inflate(R.layout.items, ll); for (short i=0;i<3;i++) ll.addView(v); 
+1
source

Source: https://habr.com/ru/post/975398/


All Articles