xamarin.Forms 에서 DependencyService 를 통해 안드로이드 네이티브 AlertDialog 사용법을 간단하게 정리해 보겠습니다.
구현하는데 있어서 세가지 룰이 있습니다.
인터페이스 - 플랫폼간 기능을 공유하기 위한 인터페이스 구현
등록 - 어셈블리화 하여 DependencyService 를 통해 인스턴스화 하기 위한 특성설정
사용 - DependencyService.Get<> 을 통해 기능 사용
1. 프로젝트 생성

Xamarin Studio 를 실행하여 좌측 "New Solution" 을 클릭합니다.

프로젝트 템플릿 선택 대화상자에서 "Cross-platform" > "App" > "Blank Xamarin.Forms App" 를 선택하고 "Next" 버튼을 클릭합니다.

설정 대화상자에서 "App Name", "Identifier" 입력, "Target Platforms" 는 "Android" 에 체크를 하고, "Shared Code" 는 "Use Portable Class Library" 선택후 "Next" 버튼을 클릭합니다.

"프로젝트 이름", "Solution Name", "위치" 입력 및 "Create a project within the solution directory" 체크 후 "만들기" 버튼을 누릅니다.

위 그림과 같이 세개의 프로젝트가 생성됩니다. 그럼 "xxx.Droid" 프로젝트에서 오른쪽 마우스 클릭 후 "시작 프로젝트로 설정" 을 선택합니다.

이제 필요로 하는 기능을 정의하는 인터페이스 파일을 만들어 보겠습니다.
PCL 프로젝트(AlertDialog) 에서 "마우스 오른쪽 클릭" > "추가" > "새파일" 을 선택합니다.

새 파일 대화창에서 "General" > "빈 인터페이스" 를 선택하고 파일 이름은 "IDAlertDialog" 입력후 "New" 버튼을 클릭합니다.
[AlertDialog > IDAlertDialog.cs]
using System;
namespace AlerDialog{
public interface IDAlertDialog {
void SimpleDialog(string msg);
}
}
네이티브 AlertDialog 기능을 호출할 메소드명을 정의합니다.
"AlertDialog.Droid" 프로젝트서 AlertDialog 기능을 정의해 어셈블리화할 파일을 생성합니다. 생성과정은 위 방법과 같고 인터페이스가 아닌 "빈 클래스"로 선택하고, 파일명은 "DAlertDialog" 로 설정합니다.
[AlertDialog.Droid > DAlertDialog.cs]
using System;
using AlerDialog.Droid;using Android.App;
using Xamarin.Forms;
[assembly: Xamarin.Forms.Dependency(typeof(DAlertDialog))]
namespace AlerDialog.Droid{
public class DAlertDialog: IDAlertDialog {
public DAlertDialog () {}
public void SimpleDialog(string msg) {
AlertDialog.Builder builder = new AlertDialog.Builder (Forms.Context);
AlertDialog alertDialog = builder.Create ();
alertDialog.SetTitle ("알림!");
alertDialog.SetIcon (Android.Resource.Drawable.IcDialogAlert);
alertDialog.SetMessage (msg);
alertDialog.SetButton ("확인", (s, e) => {
alertDialog.Dismiss();
});
alertDialog.Show ();
}
}
}
위 코드에서 주의할 점은 매개변수가 없는 생성자여야 한다는 점이고, 생성자 블럭 안에서 작업은 가능합니다.
이제 마지막으로 UI 영역을 수정하겠습니다. 페이지내에 심플한 버튼을 두어 그 버튼을 클릭하면 네이티브 AlertDialog 가 보여지는 걸 구현해 보겠습니다.
[AlertDialog > AlertDialog.cs]
using System;
using Xamarin.Forms;
namespace AlerDialog{
public class App : Application {
public App () { // The root page of your application
var button = new Button {
Text = "알림창!",
};
button.Clicked += (sender, e) => {
DependencyService.Get<IDAlertDialog>().SimpleDialog("메세지 테스트");
};
MainPage = new ContentPage {
Content = new StackLayout {
VerticalOptions = LayoutOptions.Center,
Children = {
button
}
}
};
}
protected override void OnStart () {
// Handle when your app starts
}
protected override void OnSleep () {
// Handle when your app sleeps
}
protected override void OnResume () {
// Handle when your app resumes
}
}
}
코드 작성은 끝이났습니다. 이제 실행해 확인 해보겠습니다.

실행을 하면 위 그림과 같이 버튼이 보이고 그 버튼을 누르면 아래와 같은 메시지 창을 볼 수가 있습니다.

이상입니다.