如何在android xamarin中动态添加按钮到视图?

时间:2015-01-11 08:33:24

标签: c# android xamarin xamarin.android

我正在尝试使用xamarin.android在droid应用程序中动态添加一个按钮。 我需要能够这样做,因为我必须在项目期间动态添加一些东西。 下面是我正在尝试的代码。

public class FeedbackFragment : Android.Support.V4.App.Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        var view = inflater.Inflate (Resource.Layout.ChallengeFeedbackView, container, false);

        LinearLayout parentLayoutView = view.FindViewById (Resource.Id.feedbackView);//LinearLayout
        ScrollView feedbackscrollView = parentLayoutView.FindViewById (Resource.Id.scrollView1);//ScrolView

        var scrollviewInnerContainerView = feedbackscrollView.FindViewById (Resource.Id.scrollViewInnerContainer);
        scrollviewInnerContainerView.SetBackgroundColor (Android.Graphics.Color.White);//Linear Layout

        var silhouteeContainer = scrollviewInnerContainerView.FindViewById (Resource.Id.view1);//View

        Button b1 = new Button (this);
        b1.SetText ("Click Me");

        LinearLayout.LayoutParams prm = new LinearLayout.LayoutParams (LinearLayout.LayoutParams.MatchParent,LinearLayout.LayoutParams.MatchParent);

     // I want to achieve something like this
       silhouteeContainer.AddView(b1); //when i actually do this , it shows an error.

        return view;
    }
}

这就是fChallengeFeedbackView.axml看起来的样子。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/feedbackView"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView1">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/scrollViewInnerContainer">
            <View
                android:layout_width="fill_parent"
                android:layout_height="275dp"
                android:id="@+id/view1"
                android:background="#00ff00" />
            <View
                android:layout_width="fill_parent"
                android:layout_height="275dp"
                android:id="@+id/view2"
                android:background="#ff0000" />
            <View
                android:layout_width="fill_parent"
                android:layout_height="275dp"
                android:id="@+id/view3"
                android:background="#0000ff" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>

1 个答案:

答案 0 :(得分:3)

问题是您无法将子视图添加到继承自View的内容。为此,类型必须从ViewGroup继承。此类布局为LinearLayoutFrameLayoutRelativeLayout

因此,无法在AXML文件中向您声明的View个实例添加元素。