Sunday, November 24, 2013

Android: Add Scrollbars

Suppose, we want to create the following layout:

using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ScrollbarsExample
{
     [Activity (Label = "ScrollbarsExample", MainLauncher = true)]
     public class MainActivity : Activity
     {
          protected override void OnCreate (Bundle bundle)
          {
               base.OnCreate (bundle);

               var Layout = new LinearLayout (this);
               Layout.Orientation = Orientation.Vertical;

               for (int i=0; i<20; i++) {
                    var TempButton = new Button (this);
                    TempButton.Text = "Button" + i.ToString ();
                    Layout.AddView (TempButton);
               }

               SetContentView (Layout);
          }
     }
}

So a layout, in which 20 buttons are placed vertically next to each other. Probably this will not fit completely on the cellphone screen, the app is then simply "cut off".
But we can very easily add a scrollfunction to the app, that means a possibility for the user to scroll up or down and thus can see the whole layout.
For that we add as the outmost container a ScrollView. Then we add the layout via AddView() to the ScrollView, and eventually we set the layout of the application to the ScrollView:


using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace ScrollbarsExample
{
     [Activity (Label = "ScrollbarsExample", MainLauncher = true)]
     public class MainActivity : Activity
     {
          protected override void OnCreate (Bundle bundle)
          {
               base.OnCreate (bundle);

               var MyScrollView = new ScrollView (this);

               var Layout = new LinearLayout (this);
               Layout.Orientation = Orientation.Vertical;

               for (int i=0; i < 20; i++) {
                    var TempButton = new Button (this);
                    TempButton.Text = "Button" + i.ToString ();
                    Layout.AddView (TempButton);
               }

               MyScrollView.AddView (Layout);
               SetContentView (MyScrollView);
          }
     }
}

Now the user can scroll via finger movement vertically through the application.
If the layout is horizontally wider than the screen, we achieve a horizontal scrolling possibilty by using the control HorizontalScrollView.

No comments:

Post a Comment