Search code examples
c#androidxamarin.androidandroid-custom-viewcustom-view

Xamarin.Android Inflate a custom view


Another day with Xamarin.

Well, let me clear this out first-hand : I am new to android development as well as to Xamarin

So, I am trying to create a custom View in my project and trying to set(or inflate) it's view from a layout. I have created a layout and trying to inflate it from the View.

CustomLayout.axml

<?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"
android:background="#fff">
   <EditText android:layout_height="120dp"
   android:layout_width="120dp"/>
</LinearLayout>

Customlayout.cs

public class Customlayout : LinearLayout
{
    public Customlayout(Context context) : base(context)
    {
        Inin();
    }
    public Customlayout(Context context, IAttributeSet attrs) : base(context, attrs)
    {
        Inin();
    }

    public Customlayout(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
    {
        Inin();
    }
    private void Inin()
    {
        LayoutInflater inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
        View view = inflater.Inflate(Resource.Layout.CustomLayout, this, true);
        this.AddView(view);
    }
}

The code doesn't have any affect on the view. When I reference it in any other layout, it stays blank. I know my code isn't correct, I just tried this code after going through tons of Java and android related questions. I am not even sure if this is the way to go.

Any ideas on how I can inflate the view?


Solution

  • it works for me like this :

    in Customlayout.cs change Init() like this:

    private void Init()
      {  
       LayoutInflater inflater = (LayoutInflater)Context.GetSystemService(Context.LayoutInflaterService);
       View view = inflater.Inflate(Resource.Layout.customlayout, null, true);
       this.AddView(view);
      }
    

    then in your activity layout.axml :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:app="http://schemas.android.com/apk/res-auto"
       xmlns:tools="http://schemas.android.com/tools"
       android:layout_width="match_parent"
       android:layout_height="match_parent">
    
       <namespace.CustomLayout
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
       />
    </LinearLayout>