首页 > 解决方案 > 如何在 Xamarin 的滚动视图中相对于屏幕大小调整内容的大小?

问题描述

我有一堆想要堆叠的按钮,但我也希望它们可以滚动。如何将按钮的大小设置为实际屏幕大小的百分比?我已经尝试在网格布局上调整星号。

标签: c#xamlxamarin

解决方案


给你... 10 个按钮以编程方式添加到 ScrollView,每个按钮占屏幕总宽度和高度的百分比(分别为 50% 和 20%),以及一个点击处理程序...

    protected override void OnCreate(Bundle savedInstanceState) {
        base.OnCreate(savedInstanceState);

        // Get Screen Dimensions
        var dm = Resources.DisplayMetrics;
        var widthDP = dm.WidthPixels / dm.Density;
        var heightDP = dm.HeightPixels / dm.Density;
        Android.Util.Log.Info("MyApp", $"Screen Width x Screen Height = {widthDP}dp X {heightDP}dp");

        // Add 10 Buttons in a ScrollView
        var sv = new ScrollView(this);            
        var ll = new LinearLayout(this) { Orientation = Android.Widget.Orientation.Vertical };
        sv.AddView(ll);

        for (int i = 0; i < 10; i++) {
            var btn = new Button(this);
            btn.SetBackgroundColor(Color.Blue);
            btn.Text = $"Button #{i+1}";
            btn.Tag = i+1;
            btn.Click += (sender, e) => {
                Android.Util.Log.Info("MyApp", $"Button # {btn.Tag} + Clicked!");
            };
            // Make each button 50% of the total screen width and 20% of the *total* screen height
            var lp = new LinearLayout.LayoutParams(Convert.ToInt32(widthDP * .50), Convert.ToInt32(heightDP * .20));
            lp.SetMargins(0, 10, 0, 0);     // Top margin of 10
            btn.LayoutParameters = lp;
            ll.AddView(btn);
        }

        SetContentView(sv);
    }

截屏

截屏


推荐阅读