Search code examples
javaandroid-studiokotlinandroid-custom-viewprogram-entry-point

How would I connect a customView to main activity


I created one customView which is stored in the Layout directory folder. I want to use it (reference it) in main activities xml layout. I can't figure out how I would import my customView into main activity and its xml. This customView does not have its own code, its by itself. I have yet to figure out how to connect my CustomView to its own class. Once I am able to use my customView in main activity I will be placing it inside a frameViewGroup.

p.s. Is connecting a customView to an activity similar to connecting a customView to its own class?


Solution

  • If the custom view you created is through code, for example:

    package gr.example.app.ui.layouts
    
    class MyView extends View {
       ....
    }
    

    then you have to use the full package name in this case

    <gr.example.app.ui.layouts.MyView>
    

    but if you created it as an xml (let's say its name is my_view.xml) inside the resources/layouts folder like so:

    <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="verical">
    
    .....
    
    </LinearLayout>
    

    then you have to use include inside your main_activity.xml like so:

    <include
        android:id="@+id/my_custom_view" --this is optional, just another way to find the root view of layouts/my_view
        layout="@layouts/MyView"/>