Xamarin.Android 膨胀自定义视图

Xamarin.Android Inflate a custom view

又是 Xamarin 的一天。

好吧,让我先澄清一下:我是 android 开发以及 Xamarin

的新手

因此,我正在尝试在我的项目中创建自定义 View 并尝试设置(或 inflate)它的布局视图。我已经创建了一个布局并试图从 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);
    }
}

该代码对视图没有任何影响。当我在任何其他布局中引用它时,它保持空白。我知道我的代码不正确,我在经历了大量 Java 和 android 相关问题后尝试了这段代码。我什至不确定这是不是要走的路。

关于如何膨胀视图的任何想法?

试试这个

<?xml version="1.0" encoding="utf-8"?>
    <Customlayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#fff"
        android:orientation="vertical">

        <EditText
            android:layout_width="120dp"
            android:layout_height="120dp" />
    </Customlayout>

你必须给出正确的包名。它看起来像这样 your_packageName.Customlayout

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()
    {

    }
}

像往常一样在 FragmentActivity 中加载 CustomLayout.axml

它对我来说是这样的:

Customlayout.cs 中更改 Init() 如下:

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

然后在你的 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>