2013-03-08 131 views
1

我想動態地將一個佈局添加到ScrollView中。我嘗試了一切,我發現在谷歌和這裏,但沒有機會!他們中的大多數會導致「對象引用」錯誤。以下是其中一個代碼:mono for android - 動態添加布局到滾動視圖

LayoutInflater layoutInflater = (LayoutInflater) this.GetSystemService(Context.LayoutInflaterService);  
View view = new View(this); 
view = layoutInflater.Inflate(Resource.Layout.MYLAYOUT, null); 
MYSCROLLVIEW.AddView(view); 

但它會導致「對象引用未設置爲對象的實例」。

在這之後,我想使用內部MYLAYOUT控件(視圖),例如:

MYLAYOUT.textView1.Text = 「示例」;

+0

你從哪裏得到的'Exception'?爲什麼你實例化一個'View'然後丟棄它? – Cheesebaron 2013-03-08 12:52:12

+0

我得到錯誤在MYSCROLLVIEW.AddView(view);我調試了代碼,看起來在這行「視圖」對象爲空! – 2013-03-09 03:18:03

回答

1

我所做的只是欺騙了一下,並將我的動態佈局添加到ScrollView中的現有佈局中。下面是一個例子與Horizo​​ntalScrollView:

<HorizontalScrollView 
    android:layout_width="739dp" 
    android:layout_height="match_parent" 
    android:id="@+id/horizontalMessageScrollView" 
    android:layout_gravity="center_horizontal" 
    android:layout_marginTop="15dp" 
    android:scrollbars="none"> 
    <LinearLayout 
     android:orientation="horizontal" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:id="@+id/messageHolder" /> 
</HorizontalScrollView> 

,然後在我的代碼使用以下命令:

LinearLayout messageListView = FindViewById<LinearLayout>(Resource.Id.messageHolder); 

foreach (var object in objects) { 
    // create your dynamic views here.  

    View view = new View(this); 
    view = layoutInflater.Inflate(Resource.Layout.MYLAYOUT, null); 

    TextView internalTextView= view.FindViewById<TextView>(Resource.Id.internalTextView); 
    internalTextView.SetText("Hello world!", TextView.BufferType.Normal); 
    messageListView.AddView(view); 
} 
+0

非常感謝!這有幫助!但是現在,我怎樣才能訪問新視圖的元素?!例如,我有一個孩子的textview,我想爲它設置文本。 – 2013-03-09 03:50:08

+0

在該視圖中編輯以包含「視圖」和TextView示例。 – Ron 2013-03-09 13:35:49

+0

太棒了!非常感謝! – 2013-03-10 05:13:01