如图所示:可以把照片排成一行,拖动观看
XML文件 activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <HorizontalScrollView android:id="@+id/hsv_1" android:layout_width="wrap_content" android:layout_height="150dp" android:layout_gravity="center_vertical" android:background="#AA444444"> <LinearLayout android:id="@+id/image_gallery" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:orientation="horizontal"> </LinearLayout> </HorizontalScrollView> </LinearLayout>XML 文件 photoview.xml ,其中ImageView显示照片,TextView显示照片名称
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:id="@+id/imageview_1" android:layout_width="150dp" android:layout_height="120dp" android:layout_gravity="center_vertical" android:layout_margin="5dp" android:scaleType="centerInside"/> <TextView android:layout_centerInParent="true" android:id="@+id/photo_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/imageview_1" android:textSize="12dp"/> </RelativeLayout>
Java文件 MainActivity.java
public class MainActivity extends Activity { private LinearLayout myGallery; private int[] myImagesId; private LayoutInflater myInflater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myInflater=LayoutInflater.from(MainActivity.this); initData(); initView(); } private void initData(){ myImagesId=new int[]{R.drawable.binghun,R.drawable.hudie,R.drawable.huofenghuang,R.drawable.jiansheng,R.drawable.judu}; //照片都放在drawable文件夹下 } private void initView(){ myGallery=(LinearLayout)findViewById(R.id.image_gallery); for(int i=0;i<myImagesId.length;i++){ View view=myInflater.inflate(R.layout.photoview, myGallery,false); //使用inflate获取phtoview布局里面的myGallery视窗 ImageView img=(ImageView)view.findViewById(R.id.imageview_1); img.setImageResource(myImagesId[i]); TextView text=(TextView)view.findViewById(R.id.photo_name); String imageName=view.getResources().getResourceEntryName(myImagesId[i]); //获得图片的原始名字 text.setText(imageName); myGallery.addView(view); //把添加过资源后的view视图重新添加到myGallery中 } } }