Saturday, December 22, 2012

Create Android User Control

There are several ways for creating reusable UI components in Android.

The one described here is creating a new view made with other views (much like a usercontrol in .Net).

Creating an Android user control requires a layout and a class just like creating an activity.

The layout can be whatever you want and the relevant aspect is the layout root you choose.

In this example, the layout root is a Framelayout (but can be any other):



    

Then, you must create a class to handle the logic of your user control.

The base class must be the same class of the layout root.

In the example, the class extends FrameLayout as it is the layout root of the previous example:
package YourPackage;

public class YourUserControl extends FrameLayout {
    public YourUserControl(Context context) {
        super(context);
    }
    public YourUserControl(Context context, AttributeSet attrs) {
        super(context, attrs);

        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.yourusercontrollayoutid, this);

        //more code if needed
    }

    //more code
}
You reference your new UI component in xml just like any Android view by referencing the package and class name:
<YourPackage.YourUserControl />

No comments:

Post a Comment