android中gallery的使用
1,创建配置文件
<?xml version="1.0" encoding="utf-8"?> <Gallery xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gallery" android:layout_width="fill_parent" android:layout_height="wrap_content" > </Gallery>
2,编写适配器,因为Gallery 需要一个适配器填充,而且填充的必须输图片,所以。。。
package com.kang.fei.gallery; import android.content.Context; import android.content.res.TypedArray; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; public class ImageAdapter extends BaseAdapter { private Context context; int mGalleryItemBackground; private Integer[] mImageids ={ R.drawable.sample_0,R.drawable.sample_1, R.drawable.sample_2,R.drawable.sample_3, R.drawable.sample_4,R.drawable.sample_5, R.drawable.sample_6 }; public ImageAdapter(Context context){ this.context = context; //TypedArray实例是个属性的容器,context.obtainStyledAttributes()方法返回得到 TypedArray a = context.obtainStyledAttributes(R.styleable.HelloGallery); mGalleryItemBackground = a.getResourceId (R.styleable.HelloGallery_android_galleryItemBackground, 0); a.recycle(); } public int getCount() { return mImageids.length; } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ImageView i = new ImageView(context); i.setImageResource(mImageids[position]); i.setLayoutParams(new Gallery.LayoutParams(150,100)); i.setScaleType(ImageView.ScaleType.FIT_XY); i.setBackgroundResource(mGalleryItemBackground); return i; } }
3,编写一个attrs.xml文件,防止在values文件颊下
<?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="HelloGallery"> <attr name="android:galleryItemBackground"/> </declare-styleable> </resources>
4,编写主层序类
package com.kang.fei.gallery; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Gallery; import android.widget.Toast; public class GalleryActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Gallery g = (Gallery) findViewById(R.id.gallery); g.setAdapter(new ImageAdapter(this)); g.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(GalleryActivity.this, " "+position,1).show(); } }); } }
相关推荐
huha 2020-10-16
xfcyhades 2020-11-20
sgafdsg 2020-11-04
Michael 2020-11-03
fengyeezju 2020-10-14
ziyexiaoxiao 2020-10-14
业余架构师 2020-10-09
OuNuo0 2020-09-29
moses 2020-09-22
Angelia 2020-09-11
qinxu 2020-09-10
刘炳昭 2020-09-10
Nostalgiachild 2020-09-07
Nostalgiachild 2020-08-17
leavesC 2020-08-14
一青年 2020-08-13
AndroidAiStudy 2020-08-07
ydc0 2020-07-30
绿豆饼 2020-07-28