我有2个像这样的xml文件:
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用于MainActivity.
我的问题是如何在main.xml的HorizontalScrollView中动态加载3个布局items.xml到Linearlayout!
解决方法
试试这种方式,希望这可以帮助您解决问题.
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); }