饮水思源
http://txlong-onz.iteye.com/blog/934959
Overview
Gallery 是一个,View在中心锁定的水平滑动列表。
Note: Gallery 在API 16 的时候弃用了,推荐使用其他的水平滑动的控件来代替
HorizontalScrollView
ViewPager
来代替。
实现
public class HomeActivity extends AppCompatActivity {
private Gallery gallery;
private List<Integer> integerList;
private void initFindView() {
gallery = (Gallery) this.findViewById(R.id.gallery);
}
/**
* 添加一些View
*/
private void initData() {
integerList = new ArrayList<Integer>();
integerList.add(R.drawable.pet1);
integerList.add(R.drawable.pet2);
integerList.add(R.drawable.pet3);
integerList.add(R.drawable.pet4);
integerList.add(R.drawable.pet5);
integerList.add(R.drawable.pet6);
integerList.add(R.drawable.pet7);
integerList.add(R.drawable.pet8);
integerList.add(R.drawable.pet9);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
initFindView();
initData();
GalleryImageAdapter adapter = new GalleryImageAdapter(this, this.integerList);
this.gallery.setAdapter(adapter);
//设置监听器
gallery.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(HomeActivity.this, "onItemSelected", Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
Toast.makeText(HomeActivity.this, "onNothingSelected", Toast.LENGTH_SHORT).show();
}
});
}
}
/**
* Gallery 所用到图片的适配器
*/
public class GalleryImageAdapter extends BaseAdapter {
private Context context;
private List<Integer> integerList;
public GalleryImageAdapter(Context context, List<Integer> integerList) {
this.context = context;
this.integerList = integerList;
}
@Override
public int getCount() {
return integerList.size();
}
@Override
public Object getItem(int i) {
return integerList.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
View currentView = view;
if (currentView == null) {
currentView = View.inflate(this.context, R.layout.item_img, null);
}
ImageView iv = (ImageView) currentView.findViewById(R.id.itemImg);
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setImageResource(integerList.get(i));
return currentView;
}
}