0, the use of Gallery review
we sometimes see a dynamic picture on an iphone or on windows, moving it with a mouse or a finger touch, creating a dynamic picture scrolling effect, and triggering other event responses depending on your click or touch. Similarly, this implementation is also available on Android, which is the implementation of thumbnail browsers on the UI via gallery.
Let's see how gallery is implemented by first declaring the control from the layout file, just knowing the ID is gallery.
Gallery Gallery = (Gallery) Findviewbyid (r.id.gallery);
In general, we use a control like this in Android, and we need to give it an adapter so that it can display the content in the way we define it, so we'll add an adapter to it, and as to how this adapter is implemented, then it's followed by the operation, Just know this adapter class is called
Imageadapter. Gallery.setadapter (This) (new Imageadapter);
Copy code next is the play, the adapter can be said to be the most important, let's see how to do? There seems to be a lack of something important here? What kind of things? What we need to show is the picture, then of course we have to be ready first, here we have 5 pictures (stored in the drawable folder), we use their IDs indexed to use in the adapter.
Private integer[] MPs = {
R.drawable.icon1,
r.drawable.icon2,
R.drawable.icon3,
R.drawable.icon4,
R.drawable.icon5
};
OK, this will start defining the adapter, by inheriting Baseadapter to implement the adapter.
public class Imageadapter extends Baseadapter {
private context mcontext;
Public Imageadapter {
Mcontext = context;
}
public int GetCount () {return
mps.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 image = new ImageView (mcontext);
image.setimageresource (Mps[position]);
Image.setadjustviewbounds (true);
Image.setlayoutparams (New Gallery.layoutparams (
layoutparams.wrap_content, layoutparams.wrap_content));
return image;
}
At this point, the whole gallery is basically finished first, we also need to add a listener for it, otherwise this thumbnail browser will only be able to see the use of.
Gallery.setonitemselectedlistener (New Adapterview.onitemselectedlistener () {
@Override public
Void Onitemselected (adapterview<?> parent, View v,int position, long ID) {
}
@Override public
Void onnothingselected (adapterview<?> arg0) {
//here does not respond
}
});
A, the effect chart shows
Recently downloaded several mobile phone application research, sent a number of custom controls surprisingly similar, so I think in the future development, the reuse of some controls is certainly a lot of, in the home page (not load pages) will generally have a slide effect, can put ads can also put recommendations, if the picture design good-looking, The effect is generally good, since the use of gallery, but also with the example of frame effect to write (Taobao details of the interface of the merchandise picture slide show)
(1) Slide effect display:
(2) Merchandise picture Slide Show
View larger Image:
Second, part of the code description
1, the implementation of the slide effect:
Custom Gallery:DetailGallery.java
Visual Interface: Imgswitchactivity.java
Fitting class: Galleryindexadapter.java
The custom gallery mainly overrides the onfling to move to the right or to the left by pressing and letting go, part of the code is as follows:
Private Boolean Isscrollingleft (Motionevent E1, motionevent E2) {return
e2.getx () > E1.getx ();
}
@Override Public
Boolean onfling (motionevent E1, motionevent E2, float Velocityx,
float velocityy) {
int kevent;
if (Isscrollingleft (E1, E2)) {
kevent = keyevent.keycode_dpad_left;
} else {
kevent = Keyevent.keycode_ dpad_right;
}
OnKeyDown (kevent, null);
return true;
}
2, in the adaptation class Galleryindexadapter mainly completes the slide circulation playback, returns the value in GetCount inside returns the Integer.max_value, And then in the GetView, according to the position and the number of initial pictures to calculate the remainder of each cycle to which picture. Some of the code is as follows:
@Override public
int GetCount () {
//TODO auto-generated a stub return
integer.max_value
}
..... @Override public
View getview (int position, View Convertview, ViewGroup arg2) {
//TODO auto-generated method stub
ImageView ImageView = new ImageView (context);
Imageview.setbackgroundresource (Imaglist.get (Position%imaglist.size ()));
Imageview.setscaletype (SCALETYPE.FIT_XY);
Imageview.setlayoutparams (New Gallery.layoutparams (Gallery.LayoutParams.FILL_PARENT
, Gallery.LayoutParams.WRAP_CONTENT));
return imageview;
}
3, in the visual interface to achieve logical control, through the timer to refresh the slide, timer through the timing of sending messages, message reception processing mechanism received the message, on the simulation of sliding events, call Gallery Onfling method to achieve automatic picture switching effect. The selection button's display effect (RadioButton) needs to be processed in gallery's setonitemselectedlistener.
Timer and event handling 5 seconds Refresh Slide/** Show diagram controller, realize show diagram switch * * Final Handler handler_gallery = new Handler () {public void Handlemessage (Me Ssage msg) {/* Custom screen-pressed action */motionevent e1 = Motionevent.obtain (Systemclock.uptimemillis (), Systemclock.uptim
Emillis (), motionevent.action_up, 89.333336f, 265.33334f, 0); /* Custom Screen Release action */motionevent e2 = Motionevent.obtain (Systemclock.uptimemillis (), Systemclock.uptimemillis (), Motio
Nevent.action_down, 300.0f, 238.00003f, 0);
Mygallery.onfling (E2, E1,-800, 0);
/* Add press and release action to Gallery to achieve automatic sliding/super.handlemessage (msg);
}
};
protected void Onresume () {autogallery ();
Super.onresume ();
};
private void AutoGallery () {/* Set timer, automatically toggle display chart every 5 seconds * * Timer time = new timer ();
TimerTask task = new TimerTask () {@Override public void run () {Message m = new Message ();
Handler_gallery.sendmessage (m);
}
};
Time.schedule (Task, 8000, 5000); }//indicates that the button and gallery initialization process and the event listener add process//Initialize void init () {Mygallery = (detailgallery) Findviewbyid (r.id.mygallery);
Gallery_points = (radiogroup) This.findviewbyid (R.id.galleryraidogroup);
arraylist<integer> list = new arraylist<integer> ();
List.add (R.drawable.banner1);
List.add (R.DRAWABLE.BANNER2);
List.add (R.DRAWABLE.BANNER3);
List.add (R.DRAWABLE.BANNER4);
Galleryindexadapter adapter = new Galleryindexadapter (list, context);
Mygallery.setadapter (adapter);
Set Small button Gallery_point = new Radiobutton[list.size ()]; for (int i = 0; i < gallery_point.length i++) {layout = (linearlayout) inflater.inflate (R.layout.gallery_icon, nul
L);
Gallery_point[i] = (RadioButton) Layout.findviewbyid (R.id.gallery_radiobutton);
Gallery_point[i].setid (i);////* Set indicator graph button ID */INT WH = tool.dp2px (context, 10); Radiogroup.layoutparams layoutparams = new Radiogroup.layoutparams (WH, WH);
Set indicator figure size gallery_point[i].setlayoutparams (layoutparams); Layoutparams.setmargins (4, 0, 4, 0)//Set indicator figure margin value Gallery_point[i].setclickAble (false);///Set Indicator graph button cannot be clicked/Layout.removeview (Gallery_point[i]);//One child view cannot specify multiple parent views Gallery_points.addview (Gallery _point[i]//////////* Add the initialized indicator to the radiogroup of the Diagram/}///Add event void Addevn () {Mygallery.setonitemselectedlistener (new O Nitemselectedlistener () {@Override public void onitemselected (adapterview<?> arg0, View arg1, int arg2 , long Arg3) {//TODO auto-generated Method stub Gallery_points.check (gallery_point[arg2%gallery_point.length].ge
TId ());
@Override public void onnothingselected (adapterview<?> arg0) {//TODO auto-generated stub
}
});
}
4, the product picture sliding implementation process:
The picture slide effect and the above slide effect is very similar, only has some small difference in the logic processing and the interface. The
(1) Adapter class Galleryadapter.java The image scaling processing, saving memory overhead, and the picture can be scaled according to its own requirements.
Because it is the test case, so the pictures are written dead in order to distinguish, in position = 1 changed a picture public View getview (int position, View Convertview, ViewGroup parent) { TODO auto-generated Method Stub ImageView ImageView = (ImageView) layoutinflater.from (context). Inflate (r.layout.i
MG, null);
Bitmap Bitmap = null;
try {if (position = 1) {bitmap = Bitmapfactory.decodestream (Assetmanager.open ("xpic11247_s.jpg"));
Imageview.settag ("xpic11247_s.jpg");
} else{bitmap = Bitmapfactory.decodestream (Assetmanager.open ("item0_pic.jpg"));
Imageview.settag ("item0_pic.jpg");
The catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
to zoom int width = bitmap.getwidth () before loading the picture;
int height = bitmap.getheight ();
float newheight = 200;
float newwidth = width*newheight/height;
float ScaleWidth = ((float) newwidth)/width;
float ScaleHeight = ((float) newheight)/height;
Gets the Matrix matrix = new Matrix () that you want to scale. Matrix.postscale (ScaleWidth, ScaleHeight);
Get new picture Bitmap NEWBM = Bitmap.createbitmap (Bitmap, 0, 0, width, height, matrix, true);
System.out.println (Newbm.getheight () + "-----------" +newbm.getwidth ());
Imageview.setimagebitmap (NEWBM);
return ImageView;
}
(2) added a frame effect, if the picture load failed, there will be a picture compression after the size of the picture frame.
<?xml version= "1.0" encoding= "Utf-8"?> <imageview xmlns:android=
"http://schemas.android.com/apk/res/" Android "
android:id=" @+id/waterfall_image "
android:layout_width=" fill_parent "
android:layout_ height= "Fill_parent"
android:background= "@drawable/image_border"
>
</ImageView>
Third, some problems encountered in the development
1,
If you need to add the current child childview to another view, you must remove the current Childview in the current parent view, and if not, throw caused by: Java.lang.IllegalStateException exception, prompting the specified child already has a parent. You are must call Removeview () on the child ' s parent.
2, in the picture scaling, remember to handle the DP and PX direct conversion.