2017-04-05 36 views
0

我需要dinamically創建MvxFrameControll,使其充滿內容並添加到另一個佈局(FrameLayout/LinearLayout)。 我的代碼是如何dinvically在MvvmCross中添加MvxFrameControl Android

HomeScreen.axml

<?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(); 
    } 
} 

HomeScreenView

[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)); 
    } 
} 

爲什麼此代碼不能在屏幕上添加內容,以及它如何改寫正確?當我使用templateId在axml中添加SubjectBody時,它可以正常工作。但是如果我需要添加這個dinamically?

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)); 
} 

回答

0

你確定你的代碼在UI線程上運行嗎?我在一個應用程序中使用了相似的代碼,並將視圖添加到父項中。我建議你嘗試的是:

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