2013-03-08 115 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