public class MainActivity extends ActionBarActivity {
private Gallery gl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gl=(Gallery)findViewById(R.id.gallery1);
gl.setAdapter(new GalleryAdapter());
}
//自定义adapter类
class GalleryAdapter extends BaseAdapter{
//定义要展示的图片数组
int[] images=new int[]{R.drawable.bg01,R.drawable.bg02,R.drawable.bg03,
R.drawable.bg04,R.drawable.bg05,R.drawable.bg06,
R.drawable.bg07,R.drawable.bg08,R.drawable.bg09
};
@Override
public int getCount() {
// TODO Auto-generated method stub
return images.length;
}
@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 convertView, ViewGroup viewGroup) {
ImageView iv;
if(convertView==null){
convertView=new ImageView(MainActivity.this);
}
iv=(ImageView)convertView;
iv.setImageResource(images[position]);
return iv;
}
}
}
private Gallery gl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gl=(Gallery)findViewById(R.id.gallery1);
gl.setAdapter(new GalleryAdapter());
}
//自定义adapter类
class GalleryAdapter extends BaseAdapter{
//定义要展示的图片数组
int[] images=new int[]{R.drawable.bg01,R.drawable.bg02,R.drawable.bg03,
R.drawable.bg04,R.drawable.bg05,R.drawable.bg06,
R.drawable.bg07,R.drawable.bg08,R.drawable.bg09
};
@Override
public int getCount() {
// TODO Auto-generated method stub
return images.length;
}
@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 convertView, ViewGroup viewGroup) {
ImageView iv;
if(convertView==null){
convertView=new ImageView(MainActivity.this);
}
iv=(ImageView)convertView;
iv.setImageResource(images[position]);
return iv;
}
}
}