Gallery组件可以实现图片的画廊显示效果。将图片在画廊中循环播放
继承结构如下所示
java.lang.Object | |||||
? | android.view.View | ||||
|
? | android.view.ViewGroup | |||
|
|
? | android.widget.AdapterView<T extends android.widget.Adapter> | ||
|
|
|
? | android.widget.AbsSpinner | |
|
|
|
|
? | android.widget.Gallery |
在这里我们使用BaseAdapter进行数据的配置
Xml文件
<span style="font-size:18px;"><RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Gallery android:layout_marginTop="20dp" android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </RelativeLayout> </span>
JAVA文件
<span style="font-size:18px;">package com.example.gallery; import android.os.Bundle; import android.R.integer; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageView; public class MainActivity extends Activity { private Gallery gallery;//声明Gallery private int images[] = { R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4, R.drawable.a5, R.drawable.a6, R.drawable.a7, R.drawable.a8, R.drawable.a9, R.drawable.a10, R.drawable.a11, R.drawable.a12, R.drawable.a13, R.drawable.a14 };// 图片数据 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); gallery=(Gallery)this.findViewById(R.id.gallery);//获得Gallery gallery.setAdapter(new MyAdapter()); } // 新建类继承BaseAdapter class MyAdapter extends BaseAdapter{ @Override public int getCount() { // TODO Auto-generated method stub // 数据量为整形数据的最大值 return Integer.MAX_VALUE; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View myview, ViewGroup parent) { // TODO Auto-generated method stub // 新建I那个View对象 ImageView image=new ImageView(getApplicationContext()); // 设置图片数据 image.setImageResource(images[position%images.length]); // 设置图片的对齐方式 image.setScaleType(ImageView.ScaleType.FIT_XY); // 设置图片的大小 image.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // 返回ImageView return image; }} } </span>
效果如下图
Gallery就是通过Adapter装载数据然后在Ui中进行画廊的显示
下节预报:GridView网格视图