Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create custom component based on LinearLayout, declaring layout in XML

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?

like image 201
pheelicks Avatar asked May 13 '10 16:05

pheelicks


People also ask

How do we create custom components in Android?

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.

Why layouts are created using XML file?

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.

Can you create custom views How?

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.


1 Answers

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);
like image 198
Brandon O'Rourke Avatar answered Sep 24 '22 03:09

Brandon O'Rourke