gallery 浏览图片 博客分类: Android UI 界面 Android ui gallery qq空间
程序员文章站
2024-03-14 22:35:53
...
总叙:gallery严格意义地讲也是listView的一种,通过adapter加载数据成为了一种通用的方法。
例子:为实现图片浏览的效果,类似于qq空间里面查看他人图片。达到如下图所示效果:
<!--StartFragment -->
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/iv" android:layout_width="290dp" android:layout_height="290dp" android:layout_marginBottom="5dp"/> <Gallery android:id="@+id/gl" android:layout_width="fill_parent" android:layout_height="60dp" android:spacing="10dp" android:gravity="center_vertical"/> </LinearLayout> </LinearLayout>
即上面是imageview,下面是gallery
import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; public class GalleryActivity extends Activity { /** Called when the activity is first created. */ Gallery gl; ImageView iv; int imageIDs[]={ R.drawable.a,R.drawable.b,R.drawable.c, R.drawable.d,R.drawable.e,R.drawable.f, R.drawable.g };//将R文件的图片id用一个数组 MyAdapter ma; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init();//把xml文件的id传进来,初始化 ma=new MyAdapter();//适别器 gl.setAdapter(ma);//加载识别器 //监听事件 gl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub iv.setImageResource(imageIDs[arg2%imageIDs.length]); }//一组图片的不停替换,通过一个巧妙的取余运算 @Override public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub } }); } class MyAdapter extends BaseAdapter{ @Override public int getCount() { // TODO Auto-generated method stub return Integer.MAX_VALUE; }//有的人可能会问为什么不是ma。size();是因为下面的gallery列表项无限的延伸,所以 //要保证position无限的大,因为getView方法就是通过,调用position的值 @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return 0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub /用代码实现了一个gallery列表项,相信都看的懂/ ImageView iv=new ImageView(getApplicationContext()); iv.setImageResource(imageIDs[arg0%imageIDs.length]); iv.setAlpha(200); iv.setScaleType(ImageView.ScaleType.FIT_XY); iv.setLayoutParams(new Gallery.LayoutParams(103, 106)); return iv; } } private void init() { // TODO Auto-generated method stub gl=(Gallery)this.findViewById(R.id.gl); iv=(ImageView)this.findViewById(R.id.iv); } }