Gallery是一个相当于一个相册管理系统,你可以左右拖动图片实现换图片看的效果,是一个出现了比较久,但是仍旧使用的比较多的一个类。
package cn.edu.liuwei.gallery; import android.R.array; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.Gallery.LayoutParams; import android.widget.ImageView; public class MainActivity extends Activity { //定义Gallery对象 Gallery ga; int arr[]={ //找到资源文件,这些都是图片文件,放在drawable目录下 R.drawable.p01,R.drawable.p02,R.drawable.p03,R.drawable.p04,R.drawable.p05}; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //找到对应的组件(在XML中声明Gallery对象) ga=(Gallery)findViewById(R.id.ga); //设置gallery显示时每一个view所需要的view对象,这里使用baseadapter,如果 对把baseadapter不熟悉的话,请先了解再往下看 myadapter mt=new myadapter(); //为我们的组件添加适配器 ga.setAdapter(mt); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } class myadapter extends BaseAdapter{ public int getCount() { //我们知道,baseadapter是通过getcount来计算要显示多少,我们这里使用Inteer.max是整数的最大值,相当于永远不会到头,当然,如果单纯的这么设置,肯定会出现空指针,因为们只有5个图片,所以我们后续的做取模运算,从而实现无限循环看图片 return Integer.MAX_VALUE; } public Object getItem(int p) { return p; } public long getItemId(int p) { //为了不妨碍自己调用,在这里以取模方式返回 return p%5+1; } public View getView(int p, View v, ViewGroup vg) { //定义一个imageview对象 ImageView iv=new ImageView(MainActivity.this); //通过他的setimageresource方法,设置资源文件 iv.setImageResource(arr[p%5]); //是否保存宽高比 iv.setAdjustViewBounds(true); //设置图片的位置 iv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); //将设置好的imageview返回出去 return iv; } } } 当然,在这里只是实现了显示效果,你可以拖拉看图片,但图片是不能被选择的,如果你想选择的话,添加监听器即可。这边就不详述了。 实际上,当你了解了baseadapter、listview你会发现他跟listview的使用很相似,同样使用的是baseadapter。 |