2017년 1월 31일 화요일

자마린 스튜디오(Xamarin Studio)에서 비동기로 얼럿 코드를 실행하기

C#을 계속 사용했던 개발자들에게는 Task클래스가 익숙합니다. 아래의 코드를 보면 태스크를 통해 경고 메세지 결과를 처리하는 코드가 보입니다. 

<?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:DemoAlertCallback" x:Class="DemoAlertCallback.DemoAlertCallbackPage">

    <StackLayout>
        <Button Text="Invoke Alert"
                FontSize="Large"
                HorizontalOptions="Center"
                VerticalOptions="CenterAndExpand"
                Clicked="OnButtonClicked" />
        <Label x:Name="label"
                Text="Tap button to invoke alert"
                FontSize="Large"
                HorizontalTextAlignment="Center"
                VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage>

namespace DemoAlertCallback
{
    public partial class DemoAlertCallbackPage : ContentPage
    {
        bool result; 

        public DemoAlertCallbackPage()
        {
            InitializeComponent();
        }

        void OnButtonClicked(object sender, EventArgs args)
        {
            Task<bool> task = DisplayAlert("Simple Alert",
                                           "Decide on an option",
                                           "yes or ok""no or cancel");
            task.ContinueWith(AlertDismissedCallback);
            label.Text = "Alert is currently displayed"
        }
        void AlertDismissedCallback(Task<bool> task)
        {
            result = task.Result;
            Device.BeginInvokeOnMainThread(DisplayResultCallback); 
        }
        void DisplayResultCallback()
        {
            label.Text = String.Format("Alert {0} button was pressed",
                                       result ? "OK" : "Cancel"); 
        }
    }
}


실행해서 버튼을 클릭하면 결과를 확인할 수 있다.


댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

인공지능 모델의 생태계를 정리해 주신 분이 계셔서 한번 올려봅니다.

 하루가 다르게 시장이 변하고 있어서 공부하기가 벅찹니다. ㅋㅋ