Join Albert Lo for an in-depth discussion in this video Implement SquareLayout, part of Android Development: Modern Android UI Design Elements.
- [Narrator] We are almost ready to create our view holders. But before we do that, let's first create a custom view that will be used by the view holders, and that is custom view for a square layout. Let's open our Android Project View with command-one, and we select Views, right mouse, and we create a new Java class, and we will call this new class SquareRelativeLayout. SquareRelativeLayout will inherit from RelativeLayout, so let's enter that here.
Press OK. Now we press control-O, and we will add our constructors. Let's select the first three, for our constructors. Now let's scroll down and we are going to add a method called onMeasure. This is a standard framework method provided by All Views. A protected method, onMeasure takes two parameters.
The first is a widthMeasureSpec, and the other is a heightMeasureSpec. I'm going to press command-one to dismiss the Android Project View. In our onMeasure method, we will need to declare some local variables first, so let's go ahead and do that. I'm going to declare widthMode and we will call MeasureSpec.getMode, and pass in widthMeasureSpec as our parameter.
We're also going to define widthSize and we will call MeasureSpec.getSize, passing in widthMeasureSpec as well. And we will do the same thing for height. We need to define some logic, to decide whether to use width or height for our square layout. So let's declare another local variable size, and now we're going to add a criteria if widthMode is MeasureSpec.exact and we have a non-zero width size then we're going to use that, and widthSize non-zero, then we set size to widthSize.
And we're going to do a similar check for height. And we add in height size greater than zero, and we set size to heightSize. If neither of these criteria are met, then we're going to add one more check.
We're going to add some logic here, to take the smaller of widthSize or heightSize. Smaller than will use width, otherwise we will use height. Now we need to make a couple more framework calls. The first is to actually call MeasureSpec. We're going to call it here, and we'll pass in the size that we just calculated, and also a configural parameter, measure exactly.
Once we have our finalMeasureSpec, we are going to call the super method for onMeasure. And we're going to pass in our finalMeasureSpec for both width and height, and finally we will call setMeasuredDimension, and pass in the same finalMeasureSpec as our width and height. I notice that I have a syntax error up here at line 34.
So, let's go ahead and correct that as well. I'm going to scroll up to make sure everything's okay, no more errors, and now we're ready for the next step.
- Creating a custom layout with XML
- Setting up OnClick handlers
- Making API calls
- Creating custom views
- Implementing ViewHolder objects
- Signing certificates
- Adding a checkbox