- Custom Android Layouts with Your Own ArrayAdapter
- Components of the Android ArrayAdapter
- A Custom Rental ListView Showcase
- Creating Your Project
- Defining a Source Data
- Creating the XML Layout File
- Adding Images
- Populating Data for Use
- Creating a Custom ArrayAdapter Class
- ArrayAdapter Constructor
- Rendering the View with the getView Method
- Loading Our XML Layout File
- Populating the Layout File and Returning It
- Using the Custom ArrayAdapter
- Bonus – Loading Layouts Dynamically
- Bonus – Handling Click Events for Your ArrayAdapter
- Where to from here?
- How to Create a Custom Layout in Android by Extending ViewGroup Class
- Learn to create a custom Layout manager class to display a list of tags.
- Introduction to ViewGroup
- Creating Custom ViewGroup
- Add Custom ViewGroup on Activity Layout
- Define Child View Layout
- Adding Child View to Custom ViewGroup
Custom Android Layouts with Your Own ArrayAdapter
Android provides a series of different layouts to suit your apps needs. One of the quickest and easiest ways to display information to users is via the ListView component. This component creates a simple scrollable region that can display unique sets of information. The great thing about ListView s is their customizability, giving you the power to create your own data layouts. For example, to display an image on the left and a title on the right for each entry. This is possible by creating and using custom ArrayAdapter s.
In this tutorial you’re going to learn how to take a ListView and create a customized layout using an extended ArrayAdapter. Once you have these topics covered you will be able to create awesome looking scrollable lists of information.
Components of the Android ArrayAdapter
There are several interconnected smaller pieces to create your final customized ListView . You will need the following:
- A data source, generally as a list of objects
- A customized ArrayAdapter object which dictates how your information will be processed for each entry in the data source.
- A ListView in the UI that will use the customized ArrayAdapter to generate the final output
It’s easier to think of this process visually. You need a data source, an Adapter to control the layout, and the component to visually display the results
A Custom Rental ListView Showcase
As an example you will create a customized ListView which showcases rental properties. Each property will show information such as the address, featured image, price, and a summary of the description. Here’s what you can expect to see at the end.
The idea is to learn how to customize the layout, not copy my layout exactly. Once you understand how the principles work you can create a layout that works for you.
The final code for this project is on GitHub.
Creating Your Project
Create a new project in Android Studio that supports Android 4.0.3 (API 15 – Ice Cream Sandwich) and above which will cover a large part of the Android market. Add an Empty Activity and call the project Rental Properties.
Once Android Studio finishes setting up your project you should see a simple MainActivity class and a corresponding activity_main.xml layout file. This is all you need to get started.
Defining a Source Data
Before you can create a ListView you will need data to display. Since each property has a set of information, start by creating a class to set and get the information. Create a new Property class and add the following code:
This creates the structure for the class by adding private fields to hold information such as the street address, state, description etc.
Continue by creating the default Property constructor method used to create new rental properties later as the data source.
Finally define get functions for each of the properties used later to fetch the information you need.
Creating the XML Layout File
Now that you have a class, you need to define the XML layout file used by the custom ArrayAdapter to build output.
Open your projects top level res folder and find the layout sub-directory. Create a new layout file called вЂproperty_layout’, and add RelativeLayout as the root tag (this is specific to my design).
The layout design is split into three sections:
- A left section that contains the image.
- A right section that contains the address and description.
- A bottom section that contains property specifics such as the number of bedrooms, bathrooms, car spots, and the price.
When rendered it should look like the below.
Copy the following into your new layout. Here you created a nested layout where each of section / item has ID’s so you can position and populate them. Feel free to adjust the margins, positions and sizing of the elements as you see fit.
And replace the TextView in activity_main.xml with :
Adding Images
Most of the UI components are just TextView elements, but you have a single ImageView component to handle.
Each of the properties has a corresponding image drawn when the view is rendered. In this example I’ve used the name property_image_X for each of the images displayed. Since you will add 4 properties you will need 4 images, you can find the images I used here.
If you haven’t added images to an Android Studio project before, copy all the images you want added to your project and select paste on the drawable folder.
Selecting images and dragging them into the drawable folder won’t work.
Populating Data for Use
Since you have a base Property class set up and a XML file defined, you can move onto the next step of creating the data that will display in the list.
After the opening of the MainActivity class, add the ArrayList private property so that every method inside this class can access to it.
Now jump into the onCreate method inside the MainActivity class just before the closing bracket to populate the data. Customize this if you want, but note that all these fields are mandatory and need to be defined as the constructor expects (i.e. a street number first, then street name, then suburb etc).
In a real-world app you would pull this data from a web source and create objects on-the-fly. For this tutorial it’s easier to define the values in code.
Creating a Custom ArrayAdapter Class
The standard Android ArrayAdapter will display a single line of text for each entry in a list. While that might be fine for simple lists, you need the ability to supply your own layouts and populate them accordingly. You do this by creating your own ArrayAdapter class.
For simplicity I’m creating the new class inside the MainActivty class as a nested class.
Above you created a new adapter called PropertyArrayAdapter and extended it from the standard ArrayAdapter class.
You added two private fields at the top because you need methods inside the class to access the context and the list of properties.
ArrayAdapter Constructor
When extending ArrayAdapter you need to declare a constructor that passes three properties, the context , resource and the objects .
This constructor passes the entire array list of properties and also the context. Both are important and are assigned to the classes private variables for use.
Rendering the View with the getView Method
Each time the ListView needs to render an item, it calls the getView method of the adapter. Since you want to display a custom layout you need to define this method.
Since you have access to the position of the element rendered, you can get this element from the array list of rental objects. Now you have this object you can get the address, description and all other fields using the class getter methods.
Loading Our XML Layout File
The next step is using the context saved before to get the LAYOUT_INFLATER_SERVICE service from Android. Create a new LayoutInflater object and it’s this object you use to load the detail_layout XML file that will render the view.
Populating the Layout File and Returning It
Since you now have access to the XML file you can find the elements via their ID.
Fetch all the elements and then populate their content. You make the address field by concatenating the streetNumber , streetName and state fields together. Other elements such as description are either displayed as-is, or trimmed to keep the layout tidy.
The image asset is processed differently. On creation each of the properties had a corresponding image name such as property_image_1 . You use the getResources method along with getIdentifier to get the image name from the drawable directory. This will give the resource ID to populate the ImageView .
This process can be as simple or as complex as you need it to be. In our example we’re displaying a fair bit of information and ensure it’s pretty for the end user. You could trim this down to display a few sentences or expand it more to provide more functionality.
Using the Custom ArrayAdapter
Now that you have a new customized ArrayAdapter class, return to the onCreate method inside of the MainActivity class.
Below where you added the rental property data, create the new adapter:
The three properties passed into this adapter are:
- The current context (where this references the MainActivity class)
- The value of 0 for the resources ID. 0 because you don’t need a custom layout ID, the custom adapter already handles it.
- The ArrayList of rental property objects to display
The next step is attaching this new adapter to the ListView . Do this by finding the ListView and calling the setAdapter method, passing the adapter.
And that’s it!
When you run the app you should see the new customized layout defined in the XML file and configured inside the ArrayAdapter .
Bonus – Loading Layouts Dynamically
In this example you displayed all properties using property_layout.xml. This was for simplicity, as generally you want all the list items to look the same.
When each view is rendered inside the ListView , you can choose which layout you want to inflate by specifying a different layout name. You can either load an new layout for a selected item (for example a featured element) or a tweaked version for simplicity.
Return to the example and change it so that featured properties have a different layout.
Change the Property class to add a new featured field:
Add the getter function:
You also need to add it to the constructor to ensure that the passed in data has this extra information.
For the example, set property id 1 to be featured and leave the others as they are.
Copy the property_layout.xml file and rename it to property_layout_alt.xml. Make whatever changes you like, I highlighted the address and the price with a red background.
Inside the MainActivity class, jump into the getView method and change the way the XML file is inflated.
You check to see if it’s featured, and if so load the new property_layout_alt.xml file (which contains the new visual changes)
When run you should see something like this, with the featured properties using the alternate layout
Bonus – Handling Click Events for Your ArrayAdapter
Now that you have your content displayed in a great looking list, you might want to watch for click events so you can trigger actions, such as jumping to a new activity.
Return to the onCreate method inside the MainActivity class and add the following code just before the closing bracket.
You create a new onItemClickListener object and implement its onItemClick method, triggered when a user interacts with elements inside the ViewList.
In this example you’re getting the property from the list of rental properties and then setting Intent Extras via the Intent object. Once you’ve set up the extras you can start the next activity, the Detail Activity.
When a user clicks an item it will move into the detail activity. You to add the activity to your project manifest file:
Inside the next activity you can pull the Intent Extras passed at the intent stage, creating your detail activity.
Here’s the DetailActivity class:
And the related activity layout:
Where to from here?
Now that you know the basics of how to customize the ArrayAdapter class you can build awesome interfaces for your lists. The ArrayAdapter isn’t limited to the ListView component, you can also use it with the GridView or Spinner components.
Creating rich, visually impressive lists is a great way to keep your users interested. You could expand these ideas by adding scroll animations or performing different functions on each item (for example registering one an action triggered on click and another triggered on swipe).
Any comments or questions, please let me know in the comments below.
Источник
How to Create a Custom Layout in Android by Extending ViewGroup Class
Learn to create a custom Layout manager class to display a list of tags.
Join the DZone community and get the full member experience.
Introduction to ViewGroup
A ViewGroup in Android is a special view that can contain other Views. A ViewGroup can contain one or multiple children. All other standard layout managers such as LinearLayout, FrameLayout, RelativeLayout are specialized sub classes of ViewGroup class that layout their child in specific format. For example, LinearLayout layout its child one adjacent to other either vertically or horizontally.
Sometimes, due to the specific nature of the requirement, the standard layout managers are not enough. You need to extend the ViewGroup class to create your own custom layout manager.
This post will help you to deal with creating a custom Layout manager class TagLayout that will be used to display the list of tags as shown in the following screenshot.
You have to perform the following steps while creating custom Layout manager.
- Extend your class from ViewGroup class.
- You must override the onLayout() method. This method is used to place child views.
- Override onMeasure() method. The onMeasure() method will be used to for parent to determine the size of the view group based on calculating the child view size.
- The onMeasure() and onLayout() method, will contain the logic to organize the child views with in parent layout.
You can measure each of the child view height and width by calling getMeasuredWidth() and getMeasuredHeight() methods.
Creating Custom ViewGroup
Add Custom ViewGroup on Activity Layout
Now that we are ready with the view group, let us add it to the activity layout.
Define Child View Layout
You may have notice from the layout above, we will create custom layout for view group child. In this case the tag item.
Adding Child View to Custom ViewGroup
Here is what it goes in my activity. For the sake of simplicity, I am inflating 20 child views from inside for loop. You may have some complex logic to get the data from some other source.
Published at DZone with permission of Nilanchala Panigrahy , DZone MVB . See the original article here.
Opinions expressed by DZone contributors are their own.
Источник