Android has only one line of GridView

Source: Internet
Author: User

The previous time because the project needs, need a only one row of the GridView, and when the line of content more, you can swipe left and right. I started thinking about using Gallery, but now it's obsolete. Then decided to customize one.

The basic idea is to use a horizonscrollview to wrap a gridview, and then dynamically calculate the width of the GridView based on the length of the data .

First look at the effect:

The specific implementation is as follows:

The first is the layout file

<?XML version= "1.0" encoding= "Utf-8"?> <Horizontalscrollviewxmlns:android= "Http://schemas.android.com/apk/res/android"Android:id= "@+id/grid_view_container"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent" >          <LinearLayoutAndroid:layout_width= "Match_parent"Android:layout_height= "Wrap_content">                 <GridViewAndroid:id= "@+id/grid_view"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"android:gravity= "Center"/>         </LinearLayout>          </Horizontalscrollview>
View Code

Then load The data that the GridView needs to fill in the Activity and set his width dynamically

         Onerowgridview = (GridView) Findviewbyid (R.id.grid_view);         Onerowgridview.setonitemclicklistener (this);                   New Getdataasynctask ();         Getdataasynctask.execute (this. Getapplicationcontext ());
View Code

This uses an AsyncTask to load the data, because generally data loading is a more time-consuming operation, and if it is loaded directly on the Android UI thread, it can block the UI thread and lead to a bad user experience. Asynctask Detailed code is as follows:

     Private classGetdataasynctaskextendsAsynctask<context, Void, linkedlist<onerowgriditem>> {         Privatecontext Context; @OverrideprotectedLinkedlist<onerowgriditem>doinbackground (Context ... arg0) {LinkedList<OneRowGridItem> dataList =NewLinkedlist<onerowgriditem>();  This. Context = Arg0[0]; Onerowgriditem ITEMKFC=NewOnerowgriditem (); Itemkfc.settext ("KFC");             Itemkfc.setimage (Context.getresources (). getdrawable (R.DRAWABLE.KFC));                          Datalist.add (ITEMKFC); //for convenience, here directly load drawable picture below                          returndataList; } @Overrideprotected voidOnPostExecute (linkedlist<onerowgriditem>result) {Onerowgridadapter=NewOnerowgridadapter (context, result);                          Onerowgridview.setadapter (Onerowgridadapter); intItemwidth = (int) (70 *context.getresources (). Getdisplaymetrics (). density); intItemSize =result.size (); Linearlayout.layoutparams params=NewLinearlayout.layoutparams (ItemSize *itemwidth, LinearLayout.LayoutParams.WRAP_CONTENT);             Onerowgridview.setlayoutparams (params);                      Onerowgridview.setnumcolumns (itemsize); }              }
View Code

You can see that in the OnPostExecute method, the width of the gridview is dynamically set to ensure that one line shows that the rowgridadapter is custom GridView The display of each Item in the.

 Packagecom.cchen.myviews;ImportAndroid.content.Context;ImportAndroid.graphics.Color;ImportAndroid.view.LayoutInflater;ImportAndroid.view.View;ImportAndroid.view.ViewGroup;ImportAndroid.widget.BaseAdapter;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;Importjava.util.LinkedList;Importjava.util.List;/*** Created by Cchen on 2014/7/24.*/ Public classOnerowgridadapterextendsBaseadapter {PrivateList<onerowgriditem> itemList =NewLinkedlist<onerowgriditem>(); Privatecontext Context; Private intSelecteditemindex =-1;  PublicOnerowgridadapter (context context, list<onerowgriditem>categoryiconlist) {                 This. itemList =categoryiconlist;  This. Context =context; }          Public voidSetSelection (intindex) {                 This. Selecteditemindex =index;  This. notifydatasetchanged (); }          Public intGetSelection () {return  This. Selecteditemindex;} @Override Public intGetCount () {returnitemlist.size (); } @Override PublicObject GetItem (intposition) {                returnItemlist.get (position); } @Override Public LongGetitemid (intposition) {                returnposition; } @Override PublicView GetView (intposition, View Convertview, ViewGroup parent) {Convertview= Layoutinflater.from (context). Inflate (R.layout.one_row_grid_item,NULL); ImageView ImageView=(ImageView) Convertview.findviewbyid (r.id.one_row_grid_item_image);                Imageview.setimagedrawable (Itemlist.get (position). GetImage ()); TextView TextView=(TextView) Convertview.findviewbyid (R.id.one_row_grid_item_text);                 Textview.settext (Itemlist.get (position). GetText ()); if(Position = =Selecteditemindex)                {Convertview.setbackgroundcolor (Context.getresources (). GetColor (R.COLOR.ONE_ROW_GRID_ITEM_BG)); } Else{convertview.setbackgroundcolor (color.transparent); }                 returnConvertview; }}
View Code

Among them,R. Layout.one_row_grid_item is the layout file without an item. You can see that a new selecteditemindex has been added to enable the item to be highlighted by changing his background color when a certain item is selected . Although you can use selector to define the style of Item selection and unchecked, it is limited to the finger touching the control, and when the finger leaves, it reverts to the original style. The layout of Item is as follows:

<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:id= "@+id/one_row_grid_item"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"android:gravity= "Center" >                <ImageViewAndroid:id= "@+id/one_row_grid_item_image"android:src= "@drawable/kfc"Android:layout_width= "70DP"Android:layout_height= "70DP"android:duplicateparentstate= "true"/>         <TextViewAndroid:id= "@+id/one_row_grid_item_text"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:duplicateparentstate= "true"android:ellipsize= "End"Android:singleline= "true"Android:textcolor= "#ff000000"android:textsize= "16SP"Android:text= "@string/kfc"android:layout_gravity= "Center"/> </LinearLayout>
View Code

so we basically implemented a one-line display of gridviewgridviewgridview Span lang= "en-US" >onitemclicklistener onclick method, you need to call the Span lang= "en-US" >adaptor setselection item

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.