정리가 필요한 카테고리(추후 정리)/Android, iOS

[Android] 자마린 안드로이드 가이드 따라가기 #1

TwinParadox 2017. 8. 29. 14:02
728x90

자마린 안드로이드 가이드는 다른 가이드처럼 Hello, Android로 시작한다.

Hello, Android 가이드는 두 파트로 나뉘어져 있다. 일단 하라는 대로 따라가면서 먼저 만들고 보는 Quickstart와 세부사항들에 대해서 다루고 있는 Deep Dive 두 가지로 나뉘어져 있다.


이번 포스트에서 다룰 가이드는 Quickstart로 드디어 처음으로 C#을 이용해 안드로이드 어플리케이션을 만들어 볼 차례다.


이 가이드를 보고 따라가기 앞서 두 가지 시스템 요구 사항이 존재한다.




Windows 7 이상

Visual Studio 2013 프로페셔널 혹은 그 이상 버전(커뮤니티도 가능)




자 이제 프로젝트를 생성해보자.

여타 다른 프로젝트와 다를 것 없이 프로젝트를 생성해주면 된다.






Visual C#>Android>Blank App(Android), 비어있는 앱(Android)을 선택하고, 프로젝트 이름은 Phoneword로 해주어야 한다. 그렇지 않으면 차후 문제가 발생한다. 이 부분은 다음에 설명하도록 하겠다.






솔루션 탐색기를 보면, 여러 가지 파일들이 잔뜩 생겼다.

그 중, Resources>layout>Main.axml을 더블클릭하면, 이와 같은 안드로이드 디자이너가 나타난다.

안드로이드 스튜디오를 사용해본 사람들이라면 비교적 익숙한 화면일 것이다.






IDE의 좌측 도구 상자를 누르면, 여러 가지 도구들이 나온다. 우리가 흔히 사용하는 버튼, 텍스트뷰, 리스트뷰 등등

우리가 최종적으로 원하고자 하는 형태로 설계하면 된다.





왼쪽과 같이 레이아웃을 구성하기 위해서는 오른쪽 사진에서 빨간색 박스로 표시해놓은 것만 사용 된다.



'Enter a Phoneword:' - Text(Large)

입력창 - Plaintext

두 개의 버튼(TRANSLATE, CALL) - Button





도구 상자에서 선택해서 드래그 앤 드롭 방식으로 레이아웃에 놓으면 된다.

그 후, 각자의 id와 text를 설정해주면 되는데 id와 text 설정은 '속성'에 있다. 해당 컨트롤의 속성값을 바꾸고 싶다면, 해당 컨트롤을 클릭하면(대체로 우하단에) '속성'이라는 탭에서 변경해주면 된다. Text(Large) 컨트롤을 제외한 모든 컨트롤의 id와 text를 아래 사진과 같이 바꾸어야 한다.


이후 솔루션에 새 항목 추가(Ctrl+Shift+A), Visual C#>코드 파일(Code File)을 통해 파일을 하나 생성해야 한다. 파일 이름은 'PhoneTranslator.cs'로 설정해주도록 한다. 이렇게 생성한 파일에 다음과 같은 코드를 입력한다.




using System.Text;
using System;
namespace Core
{
    public static class PhonewordTranslator
    {
        public static string ToNumber(string raw)
        {
            if (string.IsNullOrWhiteSpace(raw))
                return "";
            else
                raw = raw.ToUpperInvariant();

            var newNumber = new StringBuilder();
            foreach (var c in raw)
            {
                if (" -0123456789".Contains(c))
                    newNumber.Append(c);
                else
                {
                    var result = TranslateToNumber(c);
                    if (result != null)
                        newNumber.Append(result);
                }
                // otherwise we've skipped a non-numeric char
            }
            return newNumber.ToString();
        }
        static bool Contains(this string keyString, char c)
        {
            return keyString.IndexOf(c) >= 0;
        }
        static int? TranslateToNumber(char c)
        {
            if ("ABC".Contains(c))
                return 2;
            else if ("DEF".Contains(c))
                return 3;
            else if ("GHI".Contains(c))
                return 4;
            else if ("JKL".Contains(c))
                return 5;
            else if ("MNO".Contains(c))
                return 6;
            else if ("PQRS".Contains(c))
                return 7;
            else if ("TUV".Contains(c))
                return 8;
            else if ("WXYZ".Contains(c))
                return 9;
            return null;
        }
    }
}


성공적으로 코드 파일을 생성했다면, 이제 'MainActivity.cs'로 돌아와, Translate, Call 버튼을 구현하는 과정을 따라가자. 차근차근 따라가보도록 하자. 안드로이드 앱 개발 경험이 있는 사람들이거나 혹은 자세히 알아보고 싶지 않은 사람은, 이런 저런 부연적인 설명이 필요 없이 아래 코드를 전량 복사 붙여넣기 하면 되므로, 아래 버튼을 누르면 복사 붙여넣기할 수 있는 소스가 있다.





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

namespace Phoneword
{
    [Activity (Label = "Phoneword", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);

            // Set our view from the "main" layout resource
            SetContentView (Resource.Layout.Main);

            // New code will go here
        }
    }
}



먼저 OnCreate 메서드를 주목할 필요가 있다. 버튼에 관련한 코드는 이 메서드 안, base.OnCreate(bundle)와 SetContentView(Resource.Layout.Main) 아래에 작성될 것이다. 먼저, 템플릿 코드를 아래와 같이 바꾸도록 한다.


// Get the UI controls from the loaded layout:
EditText phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText);
Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);
Button callButton = FindViewById<Button>(Resource.Id.CallButton);




아까 안드로이드 디자이너를 통한 레이아웃을 설계해뒀다. 추가해둔 컨트롤들을 코드에서 다룰 수 있도록 다음과 같이 코드를 작성해야 한다. 코드는 SetContentView(Rexource.Layout.Main) 이후부터 적어야 한다.


// Disable the "Call" button
callButton.Enabled = false;

// Add code to translate number
string translatedNumber = string.Empty;

translateButton.Click += (object sender, EventArgs e) =>
{
    // Translate user's alphanumeric phone number to numeric
    translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
    if (String.IsNullOrWhiteSpace(translatedNumber))
    {
        callButton.Text = "Call";
        callButton.Enabled = false;
    }
    else
    {
        callButton.Text = "Call " + translatedNumber;
        callButton.Enabled = true;
    }
};


callButton.Click += (object sender, EventArgs e) =>
{
    // On "Call" button click, try to dial phone number.
    var callDialog = new AlertDialog.Builder(this);
    callDialog.SetMessage("Call " + translatedNumber + "?");
    callDialog.SetNeutralButton("Call", delegate {
           // Create intent to dial phone
           var callIntent = new Intent(Intent.ActionCall);
           callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
           StartActivity(callIntent);
       });
    callDialog.SetNegativeButton("Cancel", delegate { });

    // Show the alert dialog to the user and wait for response.
    callDialog.Show();
};



그 다음으로 Translate 버튼이 눌렸을 경우 동작하도록 해야 하는데, 바로 전에 입력했던 코드 다음에 이 코드를 입력해야 한다. Translate 버튼은 Plaintext에 입력된 문자열을 먼저 만들어놨던 'PhonewordTranslator'를 이용하여 처리하는 과정으로, 입력 값에 따라서 Call 버튼을 활성화/비활성화 시키는 작업을 실시한다.



코드 입력은 여기까지 하기로 하고, 다음 포스팅에서는 퍼미션, 아이콘, 에뮬레이터(혹은 기기)에서 구동하는 작업을 해보도록 하겠다.

728x90