Pre-ramble

I started mobile development on the iOS platform, so, naturally I'm completely spoiled. So, just as naturally, I've found a number of aspects of Android development to be very frustrating. One major frustration was creating custom views. I say was, because like just about everything in programming once a method is discovered things suddenly become less opaque than previously perceived.

The difficultly I had with creating custom views stems from the same source as majority of my android problems: terrible documentation. As a spoiled iOS developer I'm use to a thoroughly documented library complete with working examples. Android is a completely different story, but I digress. After about a week of banging my head against my keyboard, I was able to come up with an apparently novel method from creating and manipulating custom views in a simple way. I'm sure this has been done before, but I haven't seen it.

Actually Doing the Thing

The first thing to do is create an xml file for the view definition. The root element probably needs to be some kind of layout, so that children can be added. Any child elements added need to have an id unique within the file.









Next a Java Class needs to be created inheriting from the class used as the root element in the XML definition.

The Class needs to contains two constructors one that only passes the context as a parameter and another that also passes an Attribute Set. This second constructor allows xml attributes to be added to the element.

To manipulate child views, they need to be grabbed after to the xml file is loaded and ready for action. This is done by overriding the onFinishInflate method, and then finding them by id and assigning them instance variables.

package com.packagename.CustomView

public class CustomView extends LinearLayout{

public TextView text1, text2;
public ImageView icon;

public BelligerentDetailView(Context context){
super(context);
}

public BelligerentDetailView(Context context, AttributeSet attrs){
super(context, attrs);
}

@Override
protected void onFinishInflate (){
text1 = (TextView)findViewById(R.id.text1);
text2 = (TextView)findViewById(R.id.text2);
icon = (ImageView)findViewById(R.id.icon);
}

}

Return to XML definition and replace the root element with the full package name (ex. com.packagename.CustomView)





Now the custom view can be included in another XML layout file as a subview.