I have 2 xml file like this:
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.xml is used for MainActivity.
My question is how to dynamically load 3 layouts items.xml to Linearlayout in the HorizontalScrollView
of main.xml!
Try this way,hope this will help you to 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);
}
There are two ways for doing so:
Way to Left (using xml if the number of items 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>
Way to Right (In Activity using layout Inflator, if the number of items 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With