package com.example.android_23;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Gallery gallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gallery = (Gallery) findViewById(R.id.gallery1);
gallery.setAdapter(new GalleryAdapter());
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
System.out.println("您点击的是:"+arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO 自动生成的方法存根
}
});
}
class GalleryAdapter extends BaseAdapter{
private int[] images = {R.drawable.gallery_photo_1,
R.drawable.gallery_photo_2,
R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4,
R.drawable.gallery_photo_5,
R.drawable.gallery_photo_6,
R.drawable.gallery_photo_7,
R.drawable.gallery_photo_8};
@Override
public int getCount() {
return images.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView iv = null;
if(convertView==null){
convertView = new ImageView(MainActivity.this);
}
iv = (ImageView)convertView;
iv.setImageResource(images[position]);
return iv;
}
}
}
<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"
tools:context=".MainActivity" >
<Gallery
android:id="@+id/gallery1"
android:layout_width="match_parent"
android:layout_height="500dp"
/>
</RelativeLayout>