在Xamarin中创建自定义控件

时间:2014-02-10 16:03:22

标签: c# android controls custom-controls xamarin

我正在将我的应用从Windows Phone 8移植到Android - 我需要创建一些自定义UI控件。我尝试创建一个XML布局,在其中创建一个LinearLayout作为控件,然后动态添加它(在用户的愿望之后) - 但这不起作用。我怎样才能以最简单的方式实现这一目标?

这是我试过的代码:

MainActivity.cs:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace Knowledge_Organizer
{
[Activity (Label = "Knowledge_Organizer", MainLauncher = true)]
public class MainActivity : Activity
{

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);

        // Set our view from the "main" layout resource
        SetContentView (Resource.Layout.Main);

        // Import the items from resources
        LinearLayout layout = FindViewById<LinearLayout> (Resource.Id.rootLayout);

        // Add the tile
        Resource.Layout.Tile tileRoot = FindViewById<LinearLayout> (Resource.Layout.Tile);
        var tile = (Resource.Id.projectTile);
        layout.AddView (tile);
    }
}
}

主要布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px"
android:id="@+id/rootLayout" />

瓷砖:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
    android:orientation="horizontal"
    android:minWidth="25px"
    android:minHeight="25px"
    android:layout_width="290dp"
    android:layout_height="120dp"
    android:id="@+id/linearLayout1"
    android:background="#ff2e4653">
    <TextView
        android:text="Project"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:id="@+id/projectTile"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="0.0dp" />
</LinearLayout>
</LinearLayout>

提前多多感谢!

亲切的问候, 埃里克

1 个答案:

答案 0 :(得分:3)

您需要使用LayoutInflater,例如

var tile = LayoutInflater.Inflate(Resource.Layout.my_tile_xml, null);
layout.AddView (tile);

在磁贴中查找控件:

var tile = LayoutInflater.Inflate(Resource.Layout.my_tile_xml, null);
tile.FindViewById<TextView>(Resource.Id.projectTile).Text = "whatever";
layout.AddView (tile);