Android Gallery自定义风格
图片浏览gallery控件自定义风格,即加上灰色边框:
1、main.xml文件如下:
[java]
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="www.zzzyk.com"
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Gallery
android:id="@+id/Gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
/>
</RelativeLayout>
2、attrs.xml文件如下:
[java]
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery1">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
3、Activity代码如下:
[java]
public class gallery extends Activity {
private int size;
private List<Drawable> list = new ArrayList<Drawable>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
final Object data = getLastNonConfigurationInstance();
if(data == null){
getImage();
}else{
list = (List<Drawable>) data;
}
final Gallery g = (Gallery) findViewById(R.id.Gallery);
g.setAdapter(new ImageAdapter(this,list));
//默认显示Gallery的中间一个图片
g.setSelection(size/2);
}
@Override
public Object onRetainNonConfigurationInstance() {
return list;
}
//获取系统应用的图标
private List<Drawable> getImage(){
PackageManager packageManager = this.getPackageManager();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> infos = packageManager.queryIntentActivities(intent, 0);
for(ResolveInfo info : infos){
ActivityInfo ai = info.activityInfo;
Drawable icon = ai.loadIcon(packageManager);
list.add(icon);
}
return list;
}
}
4、适配器代码如下:
[java]
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackGround;
private Context mContext;
private List<Drawable> list;
public ImageAdapter(Context mContext,List<Drawable> li) {
this.mContext = mContext;
this.list = li;
TypedArray a = mContext.obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackGround = a.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public int getCount() {
return list.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// 声明一个ImageView对象
ImageView i = new ImageView(mContext);
BitmapFactory.Options options = new BitmapFactory.Options();
//设置图片的大小,宽高都为原来的二分之一,即图片为原来的四分之一
options.inSampleSize = 2;
i.setImageDrawable(list.get(position));
//设置layout的宽高
i.setLayoutParams(new Gallery.LayoutParams(200,200));//layout
//重新设置图片的宽高
i.setScaleType(ImageView.ScaleType.FIT_XY);//set scale type
//设置图片的背景,即自定义的背景风格
i.setBackgroundResource(mGalleryItemBackGround);
return i;
}
class ViewHolder{
ImageView image;
}
}
作者:huweilong1030
补充:移动开发 , Android ,