TabbedPage 는 각 화면에서 좌우 스크롤을 하면 옆 페이지로 이동합니다.

그런데 이를 막고 싶을때가 있습니다.

만약 좌우 스크롤이 탭안의 페이지에서 사용될때가 그 경우가 되겠죠

이를 막는 방법은 TabbedPage 의 소스상에서 아래의 코드를 넣어주면 됩니다.

 

this.On<Xamarin.Forms.PlatformConfiguration.Android>().SetIsSwipePagingEnabled(false); 

아래처럼 좌우 스크롤을 해도 탭페이지가 이동되지 않습니다.

 

 

 

 

ListView 에서 선택한 셀에 대한 색상을 변경하는 방법입니다.

아래는 기본 적인 ListView 코드입니다.

        <ListView x:Name="originalListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

위처럼 Page 에 위치 시킨 후 구동하면 아래와 같이 선택한 컬럼에 대해서 아래와 같이 나타납니다.

(선택 색상이 전혀 어울리지 않습니다.^^; - 안드로이드 버젼별로 색이 다름)

 

이상한 자주색이 맘에 들지 않습니다.; 선택한 컬럼에 대해 색상을 변경해봅시다.

먼저 .Net Standard 프로젝트에 ExtendedViewCell 클래스를 추가합니다.

using Xamarin.Forms;

namespace Test.Extended
{
    public class ExtendedViewCell : ViewCell
    {
        public static readonly BindableProperty SelectedBackgroundColorProperty =
            BindableProperty.Create("SelectedBackgroundColor",
                                    typeof(Color),
                                    typeof(ExtendedViewCell),
                                    Color.Default);

        public Color SelectedBackgroundColor
        {
            get { return (Color)GetValue(SelectedBackgroundColorProperty); }
            set { SetValue(SelectedBackgroundColorProperty, value); }
        }
    }
}

여기선 단순히 SelectedBackgroundColor 속성을 선언만 할 뿐입니다.

실질적인 동작은 각 장치별 렌더러에서 맡아서 처리하게됩니다.

 

Android 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Android.Content;
using Android.Graphics.Drawables;
using Android.Views;
using Test.Droid.ExtendedRenderer;
using Test.Extended;
using System.ComponentModel;
 
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.Droid.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        private Android.Views.View cellCoreView;
        private Drawable unSelectedBackground;
        private bool isSelected;

        protected override Android.Views.View GetCellCore(
            Cell item, Android.Views.View convertView, ViewGroup parent, Context context)
        {
            this.cellCoreView = base.GetCellCore(item, convertView, parent, context);

            this.isSelected = false;
            this.unSelectedBackground = cellCoreView.Background;

            return cellCoreView;
        }

        protected override void OnCellPropertyChanged(object sender, PropertyChangedEventArgs args)
        {
            base.OnCellPropertyChanged(sender, args);

            if (args.PropertyName == "IsSelected")
            {
                this.isSelected = !this.isSelected;

                if (this.isSelected)
                {
                    var extendedViewCell = sender as ExtendedViewCell;
                    this.cellCoreView.SetBackgroundColor(extendedViewCell.SelectedBackgroundColor.ToAndroid());
                }
                else
                {
                    this.cellCoreView.SetBackground(this.unSelectedBackground);
                }
            }
        }
    }
}

 

iOS 프로젝트로 가서 ExtendedViewCellRenderer 클래스를 추가합니다.

using Test.Extended;
using Test.iOS.ExtendedRenderer;
using UIKit;

using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;

[assembly: ExportRenderer(typeof(ExtendedViewCell), typeof(ExtendedViewCellRenderer))]
namespace Test.iOS.ExtendedRenderer
{
    public class ExtendedViewCellRenderer : ViewCellRenderer
    {
        public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
        {
            var cell = base.GetCell(item, reusableCell, tv);
            var view = item as ExtendedViewCell;
            cell.SelectedBackgroundView = new UIView
            {
                BackgroundColor = view.SelectedBackgroundColor.ToUIColor(),
            };

            return cell;
        }
    }
}

사전 작업은 완료되었습니다.

 

이제 기본 코드에서 ExtendedViewCell 을 사용하도록 변경합니다. (굵게표시된부분)

        <ListView x:Name="extendedListView"
                  RowHeight="30"
                  SeparatorVisibility ="Default"
                  SeparatorColor="Black"
                  Margin="10"                  >
            <ListView.Header>
                <StackLayout Orientation="Horizontal"
                             VerticalOptions="CenterAndExpand"
                             Padding="0"
                             Spacing="0"
                             BackgroundColor="Gray"
                             HeightRequest="30">
                    <Label  Text="항목"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            FontSize="12"
                            WidthRequest="80"/>
                    <Label  Text="데이터1"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                    <Label  Text="데이터2"
                            HorizontalOptions="CenterAndExpand"
                            VerticalOptions="Center"
                            TextColor="Black"
                            HorizontalTextAlignment="Center"
                            WidthRequest="80"
                            FontSize="12"/>
                </StackLayout>
            </ListView.Header>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <extended:ExtendedViewCell SelectedBackgroundColor="LightGray">
                        <ViewCell.View>
                            <StackLayout>
                                <StackLayout VerticalOptions="CenterAndExpand"
                                             Orientation="Horizontal"
                                             Padding="0"
                                             Spacing="0">
                                    <Label  Text="{Binding Content}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data1}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                    <Label  Text="{Binding Data2}"
                                            HorizontalOptions="CenterAndExpand"
                                            VerticalOptions="Center"
                                            TextColor="Black"
                                            HorizontalTextAlignment="Center"
                                            WidthRequest="80"
                                            FontSize="12"/>
                                </StackLayout>
                            </StackLayout>
                        </ViewCell.View>
                    </extended:ExtendedViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>

Selected Color 로 LightGray 를 설정한 결과는 아래과 같습니다.

완료!

Text 에 Animation 을 적용하여 글자가 순서대로 커졌다가 작아지는 효과를 주는 방법입니다.

.NET Standard 프로젝트에 클래스를 추가하여 아래와 같이 코딩합니다.

using Xamarin.Forms;

namespace Test.Cntrol
{
    public class AnimationText : StackLayout
    {
        private const string AnimationName = "AnimatedTextAnimation";

        public static readonly BindableProperty IsRunningProperty
            = BindableProperty.Create(nameof(IsRunning), typeof(bool), typeof(AnimationText), default(bool));

        public static readonly BindableProperty TextProperty
            = BindableProperty.Create(nameof(Text), typeof(string), typeof(AnimationText), default(string));

        private Animation animation;

        public AnimationText()
        {
            Orientation = StackOrientation.Horizontal;
            Spacing = -1;
        }

        public bool IsRunning
        {
            get => (bool)GetValue(IsRunningProperty);
            set => SetValue(IsRunningProperty, value);
        }

        public string Text
        {
            get => (string)GetValue(TextProperty);
            set => SetValue(TextProperty, value);
        }

        public Color TextColor { get; set; } = Color.Blue;

        protected override void OnPropertyChanged(string propertyName = null)
        {
            base.OnPropertyChanged(propertyName);

            if (propertyName == nameof(IsRunning) && IsEnabled)
            {
                if (IsRunning)
                {
                    StartAnimation();
                }
                else
                {
                    StopAnimation();
                }
            }

            if (propertyName == nameof(Text))
            {
                InitAnimation();
            }
        }

        private void InitAnimation()
        {
            this.animation = new Animation();
            Children.Clear();

            if (string.IsNullOrWhiteSpace(Text)) return;

            var index = 0;
            foreach (var textChar in Text)
            {
                var label = new Label
                {
                    Text = textChar.ToString(),
                    TextColor = this.TextColor,
                    FontAttributes = FontAttributes.Bold,
                    FontSize = 12
                };

                Children.Add(label);

                var oneCharAnimationLength = (double)1 / (Text.Length + 1);

                this.animation.Add(index * oneCharAnimationLength, (index + 1) * oneCharAnimationLength, 
                  new Animation(v => label.Scale = v, 1, 1.75, Easing.Linear));
                this.animation.Add((index + 1) * oneCharAnimationLength, (index + 2) * oneCharAnimationLength, 
                  new Animation(v => label.Scale = v, 1.75, 1, Easing.Linear));

                this.animation.Add(index * oneCharAnimationLength, (index + 1) * oneCharAnimationLength, 
                  new Animation(v => label.TranslationY = v, 0, -10, Easing.Linear));
                this.animation.Add((index + 1) * oneCharAnimationLength, (index + 2) * oneCharAnimationLength, 
                  new Animation(v => label.TranslationY = v, -10, 0, Easing.Linear));

                index++;
            }
        }

        private void StartAnimation()
        {
            animation.Commit(this, AnimationName, 16, (uint)Children.Count * 200, Easing.Linear, null, () => true);
        }

        private void StopAnimation()
        {
            this.AbortAnimation(AnimationName);
        }
    }
}

 

이제 Page 의 화면단에 아래와 같이 컨트롤을 위치시킵니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Test"
             xmlns:cntrol="clr-namespace:Test.Cntrol"
             x:Class="Test.MainPage">

    <StackLayout>
        <Label Text="Welcome to Xamarin.Forms!" HorizontalOptions="Center" />
        <cntrol:AnimationText Text="Welcome to Xamarin.Forms" IsRunning="True" HorizontalOptions="Center"/>
    </StackLayout>

</ContentPage>

아래는 실행결과 입니다.

안드로이드, iOS 모두 정상적으로 동작합니다.^^

 

 

 

 

오늘 부터 짬나는대로 Xamarin Forms 기초 내용부터 포스팅할 예정입니다.

오늘은 그 첫번째 시간으로 ContentPage 에 대해서 알아보겠습니다.

가장 기본인 화면뷰 로써 ContentPage 에는 어떤 컨트롤이든 위치시킬수 있습니다.

아래는 ContentPage Class 의 모습입니다.

    public class ContentPage : TemplatedPage
    {
        //
        // 요약:
        //     Backing store for the Xamarin.Forms.ContentPage.Content property.
        //
        // 설명:
        //     To be added.
        public static readonly BindableProperty ContentProperty;

        public ContentPage();

        //
        // 요약:
        //     Gets or sets the view that contains the content of the Page.
        public View Content { get; set; }

        //
        // 요약:
        //     Method that is called when the binding context changes.
        //
        // 설명:
        //     To be added.
        protected override void OnBindingContextChanged();
    }

 

크로스플랫폼 솔루션을 구성하면 기본적으로 MainPage 를 호출하도록 되어있는데요

        public App()
        {
            InitializeComponent();

            MainPage = new XamarinFormsStudy.MainPage();
        }

이 MainPage 가 ContentPage 로 구현되어있습니다.

    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
    }

라벨을 하나 추가하려면 아래처럼 Content 에 라벨을 하나 만들어 주면 됩니다.

        public MainPage()
        {
            InitializeComponent();
            Content = new Label
            {
                Text = "Hello, Forms!",
                VerticalOptions = LayoutOptions.CenterAndExpand,
                HorizontalOptions = LayoutOptions.CenterAndExpand,
            };
        }

결과

 

라벨만을 가지고 화면을 구성하는 경우는 드물기 때문에

아래처럼 윈폼의 Panel 과 같은 역할을 하는 Layout 을 먼저 선언하고

그안에 라벨을 넣어주는게 정석? 입니다.

        public MainPage()
        {
            InitializeComponent();

            Content = new StackLayout
            {
                VerticalOptions = LayoutOptions.CenterAndExpand,
                Children =
                {
                    new Label{
                                Text = "Hello, Forms!",
                                VerticalOptions = LayoutOptions.CenterAndExpand,
                                HorizontalOptions = LayoutOptions.CenterAndExpand,
                    }
                }
            };
        }

결과 화면은 위 결과화면과 동일합니다.


또한, XAML 형식으로도 화면정의가 가능합니다.

위 코드 내용을 모두 지우고 MainPage.xaml 을 아래처럼 코딩하면 결과화면이 동일하게 나오게됩니다.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinFormsStudy"
             x:Class="XamarinFormsStudy.MainPage">
    <StackLayout VerticalOptions="Center" >
        <Label Text="Hello, Forms!"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

 

참고 :

https://developer.xamarin.com/api/type/Xamarin.Forms.ContentPage/

https://www.youtube.com/watch?v=NP4Gea1j7Ig

GitHub > https://github.com/knagjun/XamarinForms

'C#.NET > Xamarin' 카테고리의 다른 글

(Xamarin Forms) 3.Layout  (0) 2017.07.05
(Xamarin Forms) 2.MasterDetailPage  (0) 2017.06.30
(Xamarin Forms) 1.ContentPage  (0) 2017.06.29
(Xamarin Forms) StartTimer  (0) 2017.06.22
(Xamarin) WiFi 접속하기  (0) 2017.06.18
(Xamarin.Android) splash screen 넣기  (0) 2017.06.17

+ Recent posts