Tuesday, 23 August 2011

Android: Make a custom view class based on your own xml layout

Here's how to make your own custom view class which extends FrameLayout and which is based on an xml layout description saved in res/layout/mycustomview.xml and defined as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="horizontal"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" >
<TextView
  android:id="@+id/lblOne"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
<TextView
  android:id="@+id/lblTwo"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />
</LinearLayout>

The above layout is a simple LinearLayout object containing two TextView objects. We define our custom view class based on this layout as follows:

public class MyCustomView extends FrameLayout {

  TextView lblOne;
  TextView lblTwo;

  public MyCustomView(Context context, String lblOneText, String lblTwoText) {
    super(context);
    LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.mycustomview, null);
    addView(view);
    lblOne = (TextView) view.findViewById(R.id.lblOne);
    lblTwo = (TextView) view.findViewById(R.id.lblTwo);
    lblOne.setText(lblOneText);
    lblTwo.setText(lblTwoText); 
  }
}

This does nothing more than setting the text of the two of TextView objects but hopefully demonstrates the general idea!

See the following link for a demonstration of how to reference a custom view class in an xml layout description:

http://adilatwork.blogspot.com/2011/08/android-reference-custom-view-in-xml.html

No comments: