I've been trying to create a Compound Control in Android 1.5 (as described here) but havn't been able to find any good examples on how to do this using an XML file to specify a layout. I'm fine with creating an Activity and then loading an xml file using the following in the constructor:
setContentView(R.layout.main);
However, I want to do this in subclass of LinearLayout - so I can use this compound component in other XML layouts. Something along the lines of:
public class CustomView extends LinearLayout
{
public CustomView(Context context) {
super(context);
setupView();
}
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
setupView();
}
public void setupView()
{
setContentView(R.layout.custom); // Not possible
}
}
What is the correct way of going about doing this?
So, this is how you create your own custom component in a few simple steps: Create the XML layout and style it to suit your needs. Derive your component class from the appropriate parent component, according to your XML layout. Add your component's business logic.
Using Android's XML vocabulary, you can quickly design UI layouts and the screen elements they contain, in the same way you create web pages in HTML — with a series of nested elements. Each layout file must contain exactly one root element, which must be a View or ViewGroup object.
Creating custom views. By extending the View class or one of its subclasses you can create your custom view. For drawing view use the onDraw() method. In this method you receive a Canvas object which allows you to perform drawing operations on it, e.g. draw lines, circle, text or bitmaps.
You have to "inflate" the layout for your custom view:
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.custom, this, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With