【问题标题】:Wrapping LinearLayout with ScrollView dynamically with Xamarin (C#)使用 Xamarin (C#) 动态包装带有 ScrollView 的 LinearLayout
【发布时间】:2017-03-25 17:03:40
【问题描述】:

您好,我正在使用 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)动态地执行此操作。这段代码生成了几个Button,放到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);

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

【问题讨论】:

    标签: c# android xml xamarin scrollable


    【解决方案1】:

    我没有安装 Xamarin 来尝试这个,但根据文档,你应该可以在这里使用相同的 AddView() 方法,因为它是 method from ViewGroupScrollView 继承 ViewGroup ( ViewGroup-&gt;FrameLayout-&gt;ScrollView):

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

    【讨论】:

    • 不适合我,“ScrollView”不包含“内容”的定义
    • 我指的是Xamarin.Forms.ScrollView,但从您的评论看来,您使用的是来自Android.Widget 命名空间的那个。尝试更新的答案...
    • 谢谢,现在可以了,我会用整个代码回答这个问题。
    【解决方案2】:

    我有办法。最后它很容易做到,我之前已经尝试过,但是当我第一次尝试时它对我不起作用,我不知道为什么。尽管如此,它现在工作正常。

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

    【讨论】:

      猜你喜欢
      • 2013-07-15
      • 2023-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多