Xamarin.Android 膨胀自定义视图

Aou*_*hid 1 c# android custom-view android-custom-view xamarin.android

与 Xamarin 的另一天。

好吧,让我直接弄清楚这一点:我是 android 开发以及 Xamarin 的新手

所以,我试图View在我的项目中创建一个自定义并尝试inflate从布局设置(或)它的视图。我创建了一个布局并试图从View.

自定义布局.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>
Run Code Online (Sandbox Code Playgroud)

自定义布局.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

关于如何扩大视图的任何想法?

Leo*_*SFT 6

它对我来说是这样的:

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);
  }
Run Code Online (Sandbox Code Playgroud)

然后在您的活动 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>
Run Code Online (Sandbox Code Playgroud)