Reprint please indicate source: http://blog.csdn.net/lmj623565791/article/details/38140505
Since gallery was discarded by Google, Google recommends using Viewpager and Horizontalscrollview to achieve the gallery effect. Indeed Horizontalscrollview can achieve gallery effect, but horizontalscrollview there is a big problem, if you are only used to show a small number of pictures, it should be no problem, But if I want Horizontalscrollview to be like Viewpager, you can bind the dataset (dynamically changing the picture) and do it, no matter how many images are not oom (Viewpager internal initialization, recycling, at most only 2 view). This blog first introduces the simple usage of horizontalscrollview, then expands on this basis, the custom Horizontalscrollview implementation of the effect we mentioned above, similar to a screen can display multiple view of the Viewpager, No more pictures are afraid of oom.
1. Simple usage of Horizontalscrollview
Horizontalscrollview is actually a subclass of Framelayout, so there can only be a direct sub-view inside. We used to do gallery effect, the preferred course is linearlayout, then the direction is set to horizontal.
1. layout file:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools " android:layout_width=" match_parent " android:layout_height=" Match_parent " >
It's simple, there's a horizontal linearlayout inside a horizontalscrollview.Mainactivity:
Package Com.example.zhy_horizontalscrollview;import Android.app.activity;import Android.os.bundle;import Android.view.layoutinflater;import Android.view.view;import Android.view.window;import Android.widget.ImageView; Import Android.widget.linearlayout;import Android.widget.textview;public class Mainactivity extends Activity{private LinearLayout mgallery;private int[] mimgids;private layoutinflater minflater; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.activity_main); minflater = Layoutinflater.from (this); InitData (); Initview ();} private void InitData () {mimgids = new int[] {r.drawable.a, r.drawable.b, R.DRAWABLE.C,R.DRAWABLE.D, R.DRAWABLE.E, R.draw ABLE.F, r.drawable.g,r.drawable.h, R.DRAWABLE.L};} private void Initview () {mgallery = (linearlayout) Findviewbyid (r.id.id_gallery); for (int i = 0; i < mimgids.length; i++ ) {View view = Minflater.inflate (R.layout.activity_indeX_gallery_item,mgallery, FALSE); ImageView img = (ImageView) View.findviewbyid (r.id.id_index_gallery_item_image); Img.setimageresource (Mimgids[i]); TextView txt = (TextView) View.findviewbyid (R.id.id_index_gallery_item_text); Txt.settext ("some info"); Mgallery.addview (view);}}}Very simple, I prepared some pictures directly under the drawble, and then loop into the Horizontalscrollview LinearLayout can, the layout of the item is saved, the back will be affixed to the source code.:
The effect is good ~ if you just need to show a few pictures, direct use on it.
The following is ready to go to the point, Horizontalscrollview no matter how many of the view is not recycled, when reaching a certain amount of time will occur oom, the following describes how to rewrite Horizontalscollview to achieve the beginning of the article said the effect.
2. Custom HorizontalscrollviewThought:
1. First, depending on the size of the screen and the size of item, calculate how many item can be loaded on a screen and then load the quantity item.
2, when the user right sliding (from right to left), sliding to a certain distance, loading the next, delete the first
3, when the user left slide (from left to right), sliding to a certain distance, loading the previous one, delete the last one
Look at the final:
In order to add a certain interest, do a similar to the above album effect, support drag automatically change, and click Change ~ ~ is not great ~
1, first look at the layout file:
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:backg Round= "@android: Color/white" android:orientation= "vertical" > <framelayout android:layout_width= "fill_p Arent "android:layout_height=" 0DP "android:layout_weight=" 1 "> <imageview android:id = "@+id/id_content" android:layout_width= "fill_parent" android:layout_height= "Fill_parent" android:layout_gravity= "center" android:layout_margin= "10DP" android:scaletype= "Centercrop" android:src= "@drawable/ic_launcher"/> </FrameLayout> <com.example.zhy_horizontalscrollview. Myhorizontalscrollview android:id= "@+id/id_horizontalscrollview" android:layout_width= "Wrap_content" android:layout_height= "150DP" Android:layout_gravity= "Bottom" android:background= "@android: Color/white" android:scrollbars= "None" > <linearlayo UT android:id= "@+id/id_gallery" android:layout_width= "Wrap_content" android:layout_height = "Wrap_content" android:layout_gravity= "center_vertical" android:orientation= "Horizontal" > </LinearLayout> </com.example.zhy_horizontalscrollview. Myhorizontalscrollview></linearlayout>
No change, except to change the class name to our custom class ~
2, in order to and international standards, we also engage in a adapter, similar to Baseadapter
Package Com.example.zhy_horizontalscrollview;import Java.util.list;import Android.content.context;import Android.view.layoutinflater;import Android.view.view;import Android.view.viewgroup;import Android.widget.baseadapter;import Android.widget.imageview;import Android.widget.textview;public Class Horizontalscrollviewadapter{private Context mcontext;private layoutinflater minflater;private List<Integer> Mdatas;public Horizontalscrollviewadapter (Context context, list<integer> Mdatas) {this.mcontext = context; Minflater = Layoutinflater.from (context); this.mdatas = Mdatas;} public int GetCount () {return mdatas.size ();} Public Object getItem (int position) {return mdatas.get (position);} public long getitemid (int position) {return position;} Public View GetView (int position, View Convertview, ViewGroup parent) {Viewholder Viewholder = null;if (Convertview = = NULL {Viewholder = new Viewholder (); Convertview = Minflater.inflate (R.layout.activity_index_gallery_item, parent, false); Viewholder.miMG = (ImageView) Convertview.findviewbyid (r.id.id_index_gallery_item_image); viewholder.mtext = (TextView) Convertview.findviewbyid (R.id.id_index_gallery_item_text); Convertview.settag (Viewholder);} Else{viewholder = (Viewholder) Convertview.gettag ();} ViewHolder.mImg.setImageResource (Mdatas.get (position)); ViewHolder.mText.setText ("some info"); return Convertview;} Private class Viewholder{imageview mimg; TextView MText;}}
3, the following first look at the usage:Package Com.example.zhy_horizontalscrollview;import Java.util.arraylist;import Java.util.arrays;import Java.util.list;import Android.app.activity;import Android.graphics.color;import Android.os.Bundle;import Android.view.view;import Android.view.window;import Android.widget.imageview;import Com.example.zhy_ Horizontalscrollview. Myhorizontalscrollview.currentimagechangelistener;import Com.example.zhy_horizontalscrollview. Myhorizontalscrollview.onitemclicklistener;public class Mainactivity extends Activity{private Myhorizontalscrollview mhorizontalscrollview;private horizontalscrollviewadapter mAdapter;private ImageView mImg; Private list<integer> Mdatas = new Arraylist<integer> (Arrays.aslist (R.drawable.a, r.drawable.b, R.DRAWABLE.C, R.DRAWABLE.D,R.DRAWABLE.E, R.drawable.f, r.drawable.g, R.DRAWABLE.H,R.DRAWABLE.L)); overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); Setcontentview (r.layout.Activity_main); mimg = (ImageView) Findviewbyid (r.id.id_content); Mhorizontalscrollview = (Myhorizontalscrollview) Findviewbyid (r.id.id_horizontalscrollview); madapter = new Horizontalscrollviewadapter (this, mDatas);// Add Scroll callback Mhorizontalscrollview.setcurrentimagechangelistener (new Currentimagechangelistener () {@Overridepublic void oncurrentimgchanged (int position,view viewindicator) {Mimg.setimageresource (Mdatas.get (position)); Viewindicator.setbackgroundcolor (Color.parsecolor ("#AA024DA4"));}); /Add Click Callback Mhorizontalscrollview.setonitemclicklistener (New Onitemclicklistener () {@Overridepublic void OnClick (View view, int position) {Mimg.setimageresource (Mdatas.get (position)); View.setbackgroundcolor ("# Aa024da4 "));}); /set Adapter Mhorizontalscrollview.initdatas (Madapter);}}
It's not a bit like a ListView, initializing the data adapter, then setting up the data adapter, and then setting the various callbacks ~ ~If it is just a bunch of pictures, similar to the product switching, more simple, you do not need to set up a scrolling monitoring and click to listen to ~
4, finally see the custom Myhorizontalscrollview class
Package Com.example.zhy_horizontalscrollview;import Java.util.hashmap;import Java.util.map;import Android.content.context;import Android.graphics.color;import Android.util.attributeset;import Android.util.displaymetrics;import Android.util.log;import Android.view.motionevent;import Android.view.View; Import Android.view.view.onclicklistener;import Android.view.windowmanager;import Android.widget.horizontalscrollview;import Android.widget.linearlayout;public class MyHorizontalScrollView extends Horizontalscrollview implementsonclicklistener{/** * Callback interface when picture scrolling * * @author zhy * */public interface Currentimagechangel Istener{void oncurrentimgchanged (int position, View viewindicator);} /** * The callback when the entry is clicked * @author Zhy * */public interface onitemclicklistener{void onClick (view view, int pos);} Private Currentimagechangelistener mlistener;private onitemclicklistener monclicklistener;private static final String TAG = "Myhorizontalscrollview"; linearlayout */private Linear in/** * HorizontallistviewLayout mcontainer;/** * child element width */private int mchildwidth;/** * height of child element */private int mchildheight;/** * Index */PR of the last picture currently ivate Int mcurrentindex;/** * Subscript of the current first picture */private int mfristindex;/** * Current First view */private view mfirstview;/** * Data adapter * /private horizontalscrollviewadapter madapter;/** * Maximum number of displays per screen */private int mcountonescreen;/** * screen width */private int mSc reenwitdh;/** * Save View and position key value pair */private Map<view, integer> mviewpos = new Hashmap<view, integer> ();p ublic MyH Orizontalscrollview (context context, AttributeSet Attrs) {Super (context, attrs);//Get screen width windowmanager wm = ( WindowManager) Context.getsystemservice (context.window_service);D isplaymetrics outmetrics = new DisplayMetrics (); Wm.getdefaultdisplay (). Getmetrics (outmetrics); MSCREENWITDH = Outmetrics.widthpixels;} @Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (Widthmeasurespec, HEIGHTMEASURESPEC); Mcontainer = (linearlayout) getchildat (0);} /** * Load next picture */protected void LOadnextimg () {//Array boundary value calculation if (Mcurrentindex = = Madapter.getcount ()-1) {return;} Remove the first picture and place the horizontal scroll position 0scrollTo (0, 0); Mviewpos.remove (Mcontainer.getchildat (0)); Mcontainer.removeviewat (0);// Gets the next picture, and sets the OnClick event, and joins the container in view view = Madapter.getview (++mcurrentindex, NULL, mcontainer); View.setonclicklistener (this); Mcontainer.addview (view); Mviewpos.put (view, mcurrentindex);//Current First picture small label mfristindex++;//if a scrolling listener is set to trigger if ( Mlistener! = null) {notifycurrentimgchanged ();}} /** * Load the previous picture */protected void Loadpreimg () {//If the current is already the first one, return if (Mfristindex = = 0) return;//get subscript int that should currently be displayed as the first picture index = MC Urrentindex-mcountonescreen;if (Index >= 0) {//mcontainer = (linearlayout) getchildat (0);//Remove last int oldviewpos = MCo Ntainer.getchildcount ()-1;mviewpos.remove (Mcontainer.getchildat (Oldviewpos)); Mcontainer.removeviewat ( OLDVIEWPOS);//Put this view in the first position view view = Madapter.getview (index, NULL, Mcontainer); Mviewpos.put (view, index); Mcontainer.addview (view, 0); View.setonclicklistener (this);//horizontal scroll position Move the width of the view to the left of Pixel Scrollto (MchilDwidth, 0);//Current position--the current first displayed subscript--mcurrentindex--;mfristindex--;//callback if (Mlistener! = null) {notifycurrentimgchanged () ;}}} /** * When sliding the callback */public void Notifycurrentimgchanged () {//Clear all background colors first, when clicked will be set to blue for (int i = 0; i < Mcontainer.getchildcount ( ); i++) {Mcontainer.getchildat (i). SetBackgroundColor (Color.White);} Mlistener.oncurrentimgchanged (Mfristindex, Mcontainer.getchildat (0));} /** * Initialize data, SET data adapter * * @param madapter */public void Initdatas (Horizontalscrollviewadapter madapter) {this.madapter = MAd Apter;mcontainer = (linearlayout) getchildat (0);//Get the first viewfinal view view = Madapter.getview (0, NULL, Mcontainer) in the adapter; Mcontainer.addview (view);//force calculation of the width and height of the current view if (Mchildwidth = = 0 && Mchildheight = = 0) {int w = View.MeasureSpec.mak Emeasurespec (0,view.measurespec.unspecified); int h = View.MeasureSpec.makeMeasureSpec (0, View.MeasureSpec.UNSPECIFIED); View.measure (W, h); mchildheight = View.getmeasuredheight (); mchildwidth = View.getmeasuredwidth (); LOG.E (TAG, view.getmeasuredwidth () + "," + VieW.getmeasuredheight ()); mchildheight = View.getmeasuredheight ();//Calculate the number of viewmcountonescreen per load = (MSCREENWITDH/ Mchildwidth = = 0)? mscreenwitdh/mchildwidth+1:mscreenwitdh/mchildwidth+2; LOG.E (TAG, "mcountonescreen =" + mcountonescreen+ ", Mchildwidth =" + Mchildwidth);} Initializes the first screen element Initfirstscreenchildren (mcountonescreen);} /** * Load the first screen view * * @param mcountonescreen */public void initfirstscreenchildren (int mcountonescreen) {Mcontainer = (line arlayout) getchildat (0); Mcontainer.removeallviews (); Mviewpos.clear (); for (int i = 0; i < Mcountonescreen; i++) {View View = Madapter.getview (i, NULL, Mcontainer), View.setonclicklistener (this); Mcontainer.addview (view); Mviewpos.put ( view, i); mcurrentindex = i;} if (Mlistener! = null) {notifycurrentimgchanged ();}} @Overridepublic boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {Case MOTIONEVENT.ACTION_MOVE://LOG.E ( TAG, GETSCROLLX () + ""); int scrollx = GETSCROLLX ();//If the current scrollx is the width of the view, load the next one, remove the first if (Scrollx >= mchildwidth) { LoadnextIMG ();} If current SCROLLX = 0, set one forward and remove the last if (Scrollx = = 0) {loadpreimg ();} break;} return super.ontouchevent (EV);} @Overridepublic void OnClick (View v) {if (Monclicklistener! = null) {for (int i = 0; i < Mcontainer.getchildcount (); i++) {Mcontainer.getchildat (i). SetBackgroundColor (Color.White);} Monclicklistener.onclick (V, Mviewpos.get (v));}} public void Setonitemclicklistener (Onitemclicklistener monclicklistener) {this.monclicklistener = MOnClickListener;} public void Setcurrentimagechangelistener (Currentimagechangelistener mlistener) {this.mlistener = MListener;}}
First, load the first item, based on the width of the item to calculate how many pictures the current screen can load, and then initialize the first screen of the picture, the next is to write Ontouchevent, in which listen to the user's action_move, and then according to the distance to move the previous or next to load, Also dynamically remove invisible view, Reclaim memory ~ ~ ~
There is a map in the code that specifically stores the view and posion, primarily to provide the current view location for the click Callback, a bit like this:Android custom Viewpager makes the smart use of the map in the ever-changing image switching effect ~ ~
is not fully realize the Viewpager and Horizontalscrollview fit ~ ~ ~ ~ ~ ~Horizontalscrollview effect, Viewpager characteristics ~ ~ ~
Finally, post the rotation screen:
Can see, not only do the photo album, or the picture carousel thought is just!
If you need to use gallery similar effect in your project, be decisive in using the example above.
You crossing all right to a praise, leave a message bai ~
SOURCE Click to download