You wanted to write your own custom view. You wrote it extending View class or better still TextView or ImageView class. You even added this view within your activity using Java code and tested it successfully.
But adding views with Java is a lengthy process and is cumbersome. xml makes the process easier.
So how do you add your custom view into your layout xml file?
somelayout.xml
But adding views with Java is a lengthy process and is cumbersome. xml makes the process easier.
So how do you add your custom view into your layout xml file?
somelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Other Views -->
<com.some.name.CustomView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/cell1"/>
<!-- Other Views -->
</LinearLayout>
OK, this is how you add your view in the xml file. Please note the fully qualified class name of custom view - including the package name.
After this your activity some times gives an error - error inflating the file. Why?
Two things you need to keep in mind.
- You need at least two constructors for your customview class. One with Context as parameter. And second with Context and AttributeSet as parameters. You need both the constructors even if you do not use any custom attributes for your class
- Both these constructors should be public.
class MyCustomView extends ImageView
{
/**some code here ****/
public MyCustomView(Context ctx)
{
/* your code **/
}
public MyCustomView(Context ctx, AttributeSet attrs)
{
/** code **/
} }
Now your View will be available in the activity.
Note : My experience has been, the more code you leave to the library, better for you. Specifically measurements and layouts.
Comments
Post a Comment