如何在MvvmCross Android中动态添加MvxFrameControl

时间:2017-04-05 08:15:54

标签: mvvmcross

我需要使用dinamically创建MvxFrameControll,用内容对其进行充气并添加到另一个Layout(FrameLayout / LinearLayout)。 我的代码是

HomeScreen.axml

git ls-remote -h https://github.com/danielgindi/Charts.git

a7c7bb4caf7e68e1713468c3a021d0860a587ac8    refs/heads/independent-scatter
5b22fa99ef80f2004a7439ee6d3c1cfc9c4be010    refs/heads/legacy/v2
f23e872e7573f8c79862ff4822cfc5683703d424    refs/heads/master
03939328cd995043877f97daa1c75c0d5a3ab60c    refs/heads/xcode-8.3

HomeScreenView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<krista.fm.iMonitoring.Android.Native.TopBar
    android:layout_width="match_parent"
    android:layout_height="50dp"
    local:MvxBind="DataContext TopBar"
    local:MvxTemplate="@layout/topbar"
    android:id="@+id/TopBar" />
<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/SubjectBodyContainer" />
 </LinearLayout>


public class SubjectBody : MvxFrameControl
{
    public SubjectBody (Context context, IAttributeSet attrs) : base (context, attrs)
    {
    }

    public SubjectBody (int templateId, Context context, IAttributeSet attrs) : base (context, attrs)
    {            
    }

    protected override void OnContentSet ()
    {
        base.OnContentSet ();
    }
}

为什么此代码不会在屏幕上添加内容以及如何正确重写?当我在使用templateId在axml中添加SubjectBody时,它可以正常工作。但是,如果我需要添加这个dinamically怎么办?

[Activity (Label = "HomeScreen")]
public class HomeScreenView : MvxActivity
{
    public override void OnAttachedToWindow()
    {
        base.OnAttachedToWindow();
    }

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        SetContentView (Resource.Layout.HomeScreen);

        AddSubjectBody();
    }

    protected override void OnStart()
    {
        base.OnStart();
    }

    protected virtual void AddSubjectBody()
    {
        var container = FindViewById<FrameLayout>(Resource.Id.SubjectBodyContainer);
        var subjectBody = new SubjectBody(Resource.Layout.SubjectBody, this, null);
        subjectBody.DataContext = new SubjectBodyViewModel();

        container.AddView(subjectBody, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent));
    }
}

1 个答案:

答案 0 :(得分:0)

您确定您的代码在UI线程上运行吗?我在一个应用程序中使用了相似的代码,并将视图添加到父级中。我建议你尝试的是:

this.RunOnUiThread(() => container.AddView(this.subjectBody));