Overview

Gallery 是一个,View在中心锁定的水平滑动列表。

Note: Gallery 在API 16 的时候弃用了,推荐使用其他的水平滑动的控件来代替HorizontalScrollView ViewPager来代替。

Android Gallery_ide

实现

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;
    }
}

除非特殊声明否则,本博客文章均属 鲁迅认识的那只猹 原创,未经许可禁止转载,否则将保留追究法律责任的权利。

如果本博客损害了您的相关权益,请及时联系我,我将妥善处理。 Email: wangyidong_cn@outlook.com