"Turn" Pro Android Learning Note (22): User interface and Control (10): Custom Adapter

Source: Internet
Author: User

Directory (?) [-]

    1. Design the layout of the adapter
    2. Code section
      1. Activity's Code
      2. Code data sources and constructors for Myadapter
      3. The Myadapter code implements the custom adapter
      4. Myadapter's code continues to explore Baseadapter

We can inherit the abstract class Baseadapter to implement their own adapter, set the child view of the UI, different sub-view can be different layouts, and their own data and sub-view of the corresponding relationship between the data. Figure is the result of the example, we have a lot of icons, the icons are scaled by a certain size, and then laid out in the GridView. This example is simple.

Design the layout of the adapter

Activity layout is simple, there is only one GridView, we continue to use the previous GridView example XML file, see Pro Android Learning Note (20): User interface and Control (8): GridView and Spinner, Do not repeat.

We design each grid, that is, the layout of the sub-view, ui_gridimage.xml the following, also very simple, containing only one control Imageview,id to R.id.ui_myimage.

<?xml version= "1.0" encoding= "Utf-8"?>
<imageview xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:id= "@+id/ui_myimage"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:background= "#555"
Android:scaletype= "Centerinside"
Android:padding= "5dip"
android:maxheight= "50dip"
Android:maxwidth= "50dip"/>

Code part of activity

Since this example is small, the custom adapter is placed in the activity in the form of an inner class, and should generally be independent of a class. The activity code is as follows:

public class UiGridCustomTest1 extends activity{
/* and the system-provided adapter method is not different on the call, but we will get the data directly in the Myadapter, and directly specify how to render, do not need to pass the data source and other information. */
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.ui_gridview);
GridView GV = (GridView) Findviewbyid (R.id.ui_grid);
Myadapter adapter = new Myadapter (this);
Gv.setadapter (adapter);

}
/* Myadatpter is a custom adapter. This example appears in the inner class mode */
Private class Myadapter extends Baseadapter{
......
}
}

Next, we'll focus on the Myadapter code.

Myadapter code: Data Sources and constructors

Private class Myadapter extends baseadapter{
private static final String tag= "Myadapter"; For LOG.D (TAG, ...);
Private Context mcontext = null;
Private Layoutinflater infalter = null;

/ * "Data source (1)": icons[] is the ID of the image resource, is the original data, the production of bitmap picture through the resource ID myimages[], this is the original size of the picture, in fact, we have to do the image scaling, placed in mythumbs[], And Mythumbs is a picture that needs to be rendered in the UI. */
Private int[] icons = {r.drawable.png01,r.drawable.png02,... (omitted) ..., r.drawable.png20};
Private bitmap[] MyImages = new Bitmap[icons.length]; Original
Private bitmap[] Mythumbs = new Bitmap[icons.length]; Scaling drawings by size

private int convertviewcount = 0; Used for trace information in LOG.D.

/ * For storing controls in child view, this example has only one and is relatively simple. */
Private Class viewholder{
ImageView image;
}

Public Myadapter (Context context) {
/* "Initialize (1)": Save context, create Infalter, and associate with context. Infalter is handy for creating view objects from XML. */
Mcontext = context;
Infalter = Layoutinflater.from (Mcontext);
/* "Initialize (2)" "Data Source (2)": Create a data source to convert the resource ID to the final rendered bitmap information */
for (int i = 0; I <icons.length; i + +) {
Myimages[i] = Bitmapfactory.decoderesource (Context.getresources (), icons[i]);
You can also use Thumbnailutils to work with related pictures and videos
Mythumbs[i] = Bitmap.createscaledbitmap (Myimages[i], [+], "false");
}
}

......

}

MyadapterCode: Implementing the Custom Adapter

Myadapter integrates abstract class Baseadapter, there are 4 abstract methods that must be implemented, actually adapter interfaces from Baseadatper implementations.

Private class Myadapter extends baseadapter{
... ...
//how Many items is in the data set represented by this Adapter.
How many item to display, this example is the number of pictures.
public int GetCount ()
{
LOG.D (TAG, "GetCount () return" + icons.length);
return icons.length;
}

//Get The data item associated with the specified position in the data set.
According to position returns the child view corresponding data, the user does not need to consider the specific UI layout to obtain the data, the criminal detention data obtains and the adapter implementation correlation, for example reads the contact person's name in the CursorAdapter example, we are through _ The ID is read from the content provider, where null can be returned directly.
Public Object getItem (int position)
{
LOG.D (TAG, "getItem (" + position + ")");
return icons[position];
}

//Get the row ID associated with the specified position in the list.
According to position get ROWID, in cursoradapter example, rowID is _id, not necessarily and position consistent, for example, in the ListView row of data line delimiter (delimiter is also a child view, Position) display methods, ROWID and position are inconsistent.
public long getitemid (int position)
{
LOG.D (TAG, "getitemid (position) is" + position);
return position;
}

//Get a View that displays the data on the specified position in the data set.
This is the implementation of the child view layout display and is the most critical part of the code. Android only asks for the rendering of the currently displayed sub-view, which is not the child view that is displayed, and the system does not call GetView (), which is a good way to improve performance. To display the use of a child view, the system calls the method according to position.
Parameter 2:convertview is a sub-view, if the first request to give the position of the child view of the rendering, Convertview is null, we scroll up and down the screen, the system will ask for the display of the individual sub-view of the specific rendering, If the child view has been created before, then Convertview is the previous child view object, and we can simplify the code and improve the efficiency by taking advantage of the previously implemented sub-view objects saved by the system. Parameter 3 parent, which is the GridView at the level of this example
Public View GetView (int position, view Convertview, ViewGroup parent){
Viewholder Holder; The control that holds the child view so that we do not have to look through the ID every time, referencing the object directly.
LOG.D (TAG, "GetView (): Position =" + position
+ "Convertview =" + (Convertview = = null? ") Null ": Convertview.tostring ())
/*+ "Parent:" + (parent = = null?) Null ": Parent.tostring ()) */);

Implementing layouts
if (Convertview = = null) {///Sub-view first appears, need to be constructed to place the important content (in this case, the control object) in Viewholder and store it through Settag ().
Convertview = infalter.inflate (r.layout.ui_gridimage, null);//CREATE VIEW with XML
Convertviewcount + +;
LOG.D (TAG, "Convertviewcount is" + convertviewcount);
Holder = new Viewholder ();
Holder.image = (ImageView) Convertview.findviewbyid (r.id.ui_myimage);
Holder.image.setImageBitmap (Mythumbs[position]);
Convertview.settag (Holder);
}else{//Sub-view has already been created, using the object that has already been used to obtain control information
Holder = (viewholder) convertview.gettag ();
LOG.D (TAG, "image is" + holder.image.toString ());
}

The picture in the view, here is a place is not very clear, if we put in convertview = = NULL, that is, only the first occurrence of the setting of the control of the picture, if we scroll up and down the screen, found that the picture shows a chaotic phenomenon, why?
Holder.image.setImageBitmap (Mythumbs[position]);
return convertview;Returns the object of the child view
}
}

MyadapterCode: continue to explore Baseadapter

To implement the above four abstract functions, and to complete our example, we continue to analyze some of the other interesting functions of baseadapter, and we can add some rewriting methods to the example.

Private class Myadapter extends baseadapter{
... ...
//Returns how many seed view to display in Adapterview, this example only imageview one, therefore returns 1. For example, the ListView returns 2 if there is a separator between the data, a row TextView, and a row separator.
public int Getviewtypecount () {

LOG.D (TAG, "in Getviewtypecount (): Only one Type");
return 1;
}

//before creating each sub-view, that is, before GetView (), call this function and ask which seed view, if there are 2 seed view, the return value is 0 or 1, if there are 3 kinds, return 0,1,2. This example has only one seed view, so no matter which position, it returns 0. In the example using separator, return 0, 1 according to parity, and also use iseanble (int position), for separator to return false.
public int Getitemviewtype (int position){
LOG.D (TAG, "in Getitemviewtype () for position" + position);
return 0;
}
}

For more examples of custom adapter, you can refer to the Android Learning Note (15): Activity-galleryview, Android learning Note (19): Build Your own listview.

RELATED Links: My Android development related articles

"Turn" Pro Android Learning Note (22): User interface and Control (10): Custom Adapter

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.