main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Activity
package ntc.gallery;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemSelectedListener;
public class GalleryActivity extends Activity {
/** Called when the activity is first created. */
private Gallery gallery;
private int[] image = new int[] { R.drawable.audio_player_bg_bottom, R.drawable.audio_player_bg_top, R.drawable.ic_launcher, R.drawable.media_player_next_button, R.drawable.media_player_play_button_on, R.drawable.media_player_play_button_on, R.drawable.media_player_prev_button_on, R.drawable.media_player_progress_button,
R.drawable.media_player_progress_bg, R.drawable.icon, };
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gallery = (Gallery) findViewById(R.id.gallery);
gallery.setAdapter(new ImageAdapter(this,image));
gallery.setSpacing(1);
gallery.setSelection(4);
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{}
public void onNothingSelected(AdapterView<?> arg0)
{}
});
}
class ImageAdapter extends BaseAdapter
{
private int[] image;
private Context context;
public ImageAdapter(Context c,int[] image)
{
context = c;
this.image=image;
}
// 获取图片的个数
public int getCount()
{
return Integer.MAX_VALUE;
}
// 获取图片在库中的位置
public Object getItem(int position)
{
return position;
}
// 获取图片ID
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView = new ImageView(context);
// 给ImageView设置资源
imageView.setImageResource(image[position % image.length]);
// 设置显示比例类型
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
// 设置布局 图片120*80
imageView.setLayoutParams(new Gallery.LayoutParams(60, 60));
return imageView;
}
}
}