使用 Xamarin (C#) 动态包装 LinearLayout with ScrollView



你好,我正在使用Xamarin(C#(,我正在尝试开发一个Android应用程序,我需要使我的内容可滚动,我知道我可以通过将XML文件更改为类似的东西来做到这一点

<ScrollView
         android:layout_width="fill_parent"
         android:layout_height="wrap_content">
                <LinearLayout 
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:orientation="vertical">
                      <!-- Content here -->
                </LinearLayout>
</ScrollView>

但我需要使用 C#(和 Xamarin(动态执行此操作。这段代码生成几个按钮并将它们放入 linearLayout,但我需要将 linearLayout 放入 scrollView 中才能向下滚动并查看其他按钮。

var linearLayout = new LinearLayout(this);
var scrollView = new ScrollView(this);
int count = 30;
linearLayout.Orientation = Orientation.Vertical;
....
for (int a = 1; a < count; a++)
                {
        var button = new Button(this);                        
            linearLayout.AddView(Button);
        }
SetContentView(linearLayout);

感谢您的回复或提示,如何提前以其他方式进行操作。

我没有安装Xamarin来尝试这个,但是根据文档,您应该能够在此处使用相同的AddView()方法,因为它是来自ViewGroup的方法,并且ScrollView继承了ViewGroup(ViewGroup -> FrameLayout -> ScrollView(:

scrollView.AddView(linearLayout);
SetContentView(scrollView);

我有解决方案。最后这很容易做到,我以前已经尝试过了,但是当我一开始尝试它时,它对我不起作用,我不知道确切的原因。尽管如此,它现在工作正常。

var linearLayout = new LinearLayout(this);
linearLayout.LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
var scrollView = new ScrollView(this);
scrollView.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
scrollView.AddView(linearLayout);
int count = 30;
linearLayout.Orientation = Orientation.Vertical;
....
for (int a = 1; a < count; a++)
                {
        var button = new Button(this);                        
            linearLayout.AddView(Button);
        }
SetContentView(scrollView);

最新更新