首页 > 代码库 > Gallery的使用

Gallery的使用

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,ViewSwitcher.ViewFactory{    private int[] res={R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher,R.mipmap.ic_launcher};;    private Gallery gallery;    private ImageAdapter imageAdapter;    private ImageSwitcher imageSwitcher;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        gallery=(Gallery)findViewById(R.id.gallery);        imageSwitcher=(ImageSwitcher)findViewById(R.id.imageswitcher);        imageAdapter=new ImageAdapter(res,this);        gallery.setAdapter(imageAdapter);        //设定gallery的监听器        gallery.setOnItemSelectedListener(this);        //通过Viewfactory的接口为imageswitcher创建一个视图        imageSwitcher.setFactory(this);    }    //给imageswitcher设定选中的图片的资源    @Override    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {        imageSwitcher.setBackgroundResource(res[i]);    }    @Override    public void onNothingSelected(AdapterView<?> adapterView) {    }    //设定所要设计的接口视图返回imageview的对象;适用于设置viewswitcher    @Override    public View makeView() {        ImageView imageView= new ImageView(this);        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);        return imageView;    }}

设定一个Gallery和一个viewswitcher,显示所选择的视图(通过设置Onitemseletedlistener监听器和viewfactory的接口),其中Onitemselectedlistener监听器设置所imageswitcher所选择的视图,在viewfactory接口中实现返回一个imageview得对象

public class ImageAdapter extends BaseAdapter {    private Context context;    private int[] res;    //通过构造函数来传递数据    public ImageAdapter(int[]res, Context context){        this.context=context;        this.res=res;    }    @Override    public int getCount() {        return res.length;    }    @Override    public Object getItem(int i) {        return res[i];    }    @Override    public long getItemId(int i) {        return i;    }    @Override    public View getView(int i, View view, ViewGroup viewGroup) {        ImageView imageView= new ImageView(context);        imageView.setBackgroundResource(res[i]);        imageView.setLayoutParams(new Gallery.LayoutParams(300,400));        imageView.setScaleType(ImageView.ScaleType.FIT_XY);        return imageView;    }}

自定义一个适配器,设定所要加载的图片。

Gallery的使用