Use the Custom Component

Use the Custom Component


We now have our custom component, but how can we use it? In the NotePad example, the custom component is used directly from the declarative layout, so take a look atnote_editor.xml in the res/layout folder.

<view
 
class="com.android.notepad.NoteEditor$MyEditText"
 
id="@+id/note"
 
android:layout_width="fill_parent"
 
android:layout_height="fill_parent"
 
android:background="@android:drawable/empty"
 
android:padding="10dip"
 
android:scrollbars="vertical"
 
android:fadingEdge="vertical" />
  • The custom component is created as a generic view in the XML, and the class is specified using the full package. Note also that the inner class we defined is referenced using the NoteEditor$MyEditText notation which is a standard way to refer to inner classes in the Java programming language.

    If your custom View component is not defined as an inner class, then you can, alternatively, declare the View component with the XML element name, and exclude the classattribute. For example:

    <com.android.notepad.MyEditText
     
    id="@+id/note"
      ...
    />

    Notice that the MyEditText class is now a separate class file. When the class is nested in the NoteEditor class, this technique will not work.

  • The other attributes and parameters in the definition are the ones passed into the custom component constructor, and then passed through to the EditText constructor, so they are the same parameters that you would use for an EditText view. Note that it is possible to add your own parameters as well, and we will touch on this again below.


저작자 표시 비영리 동일 조건 변경 허락
신고