package com.example.gallery;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
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 ImageAdapter(this));//设置图片适配器
//点击图片监听
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "点击了第"+arg2+"张图片",
Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
}
}
//Adpater的class
package com.example.gallery;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter{
private Context context;
private Integer[] ima;
public ImageAdapter(Context context){
this.context=context;
ima=new Integer[]{
R.drawable.ima01,
R.drawable.ima02,
R.drawable.ima03
};
}
@Override
public int getCount() {
// 返回获得的图片数目
return ima.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageview=new ImageView(context);
imageview.setImageResource(position);
imageview.setScaleType(ImageView.ScaleType.FIT_XY);
imageview.setLayoutParams(new Gallery.LayoutParams(136,88));
return imageview;
}
}
//xml
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Gallery
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:background="?android:galleryItemBackground"
/>
求各位师兄师姐解答,谢谢啦