안녕하세요! 자마린(Xamarin)관련 두번째 포스팅 시작하겠습니다.

이번 주제는 보기에는 간단한 기능이지만! 쉽게 설명되어 있는 곳이 없어서

안타까운 마음과 꼭 널리널리 알려지길 바라는 마음이었습니다..

제가 많이 초보자라서 항상 누구라도 따라하기 쉽게 가자!라는 마인드여서

따라하시는데 별 부담이 없으실겁니다^^;

이 정보가 도움이 되길 바라며,

그럼 따라해볼까요?


Hello, guys! This is the second posting about Xamarin.

Although this topic is related to basic functions, gathering information was hard for me.

So, I really hope that you guys won't have trouble in it like me.

I'm not an expert, hence, I'll explain it basically.

I hope it'll be helpful for someone who needs it.

Follow me!



네, 오늘 준비한 기능은 총 3가지입니다.
버튼 생성, 새 페이지 추가, 웹뷰 띄우기입니다!
준비 되셨나요?
※Xamarin과 Android Studio를 비교하기 위해서 똑같은 기능을 구현하는 방법을
Android studio 카테고리에 포스팅하겠습니다. 참고바랍니다.

I prepared three things which we will learn today.
They're adding buttons, adding a new page and displaying web view.
Are you guys good to go?
※ I'm posting same things in Android Studio ASAP to compare how different Xamarin and Android are.


첫번째 기능인 버튼을 생성하기 위해서는 먼저 프로젝트를 생성해줍니다!
Cross-Platform -> Blank Xaml App (Xamarin.Forms Portable)
저는 제목을 Seminar Example로 지정하였습니다.

To make buttons, let's create a project.
Cross-Platform -> Blank Xaml App (Xamarin.Forms Portable)
My project name is SeminarExample.


프로젝트를 생성하시면 위와같이 솔루션 탐색기에 여러개가 생기게 되는데
크게 4가지로 나뉩니다.
첫번째 섹션에 해당하고 노란별 두개가 있는 MainPage.xaml이 메인화면 관련 코딩부분입니다.
저 부분에 코딩을하게 되면 Android, iOS, Windows로 모두 실행이 가능합니다!
Android, iOS, Windows중 실행을 원하시는 목록에서 마우스 오른쪽 클릭하신 뒤, 시작 프로젝트로 설정을 누르시면 됩니다.

After we created the project, we can see four things.
The first part, there are two yellow stars, is the most important. In MainPage.xaml, we can design the main display.
In this facet, if I code something, it will apply to Android, iOS and Windows.
Set the start project by right clicking whatever you want to execute such as .Droid, .iOS, Windows and WinPhone.


MainPage.xaml에서 이제 화면에 관련된 레이아웃을 나누셔야 하는데요.
일단 저는 버튼 2개만 필요하니 1:1로 나누겠습니다.

We should divide this layout.
Because I need two buttons, I'll divide it by 1:1.

 
<?xml version="1.0" encoding="utf-8" ?>
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SeminarExample"
             x:Class="SeminarExample.MainPage"
             Title ="Examples">

  <RelativeLayout BackgroundColor="White">
    <Grid
        RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}"
        RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1}">

      <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="1*"/>
      </Grid.RowDefinitions>
 
여기서 타이틀 지정도 가능하며, 백그라운드 컬러도 화이트로 되어있지만
여러분이 원하시는 색깔로 바꿀수 있습니다.
Black, Green, Red, Blue 등등.
(#FFFFFF와 같이 앞에 #만 빼고 넣으면 그 색깔로 자유자재 지정 가능합니다.)
1:1로 나누기 위해서 1* 1* 라고 썼습니다!

You can write your title here.
Furthermore, you can change the background color such as black, green, red, blue, etc though I chose white colour.
(You can also use this form #FFFFFF without #)
There is 1* and 1* since we want to divide it by 1:1.


이제 레이아웃도 나누었으니 각 레이아웃에 0번 1번이라는 순서로 무엇인가 만들 수 있습니다!
저희 강의는 버튼 만들기이므로 버튼을 추가한 뒤, 세부 설정을 지정하였습니다.

In Grid.Row="0" and Grind.Row="1", you can design something in detail.
I added two buttons and their property.
 
      <StackLayout Grid.Row="0">
        <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
          <Button
              Text="NEW PAGE"
              TextColor="White"
              FontSize="30"
              BackgroundColor="#128ffa"
              x:Name="AddPageBtn"/>
        </Grid>
      </StackLayout>
      
      <StackLayout Grid.Row="1">
        <Grid VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
          <Button
                Text="Google.com"
                TextColor="White"
                FontSize="30"
                BackgroundColor="#a5b8c8"
                x:Name="GoogleBtn"/>
        </Grid>
      </StackLayout>
    </Grid>
  </RelativeLayout>
</ContentPage>


마지막이 /ContentPage 이런식으로 닫힌걸 보니
위에 코드랑 바로 이어서 쓰시면 되겠다는거 아시겠지요?
(코드 2개 썼는데 위에랑 밑에를 순서대로 복붙하신게 MainPage.xaml의 내용입니다.)

 여기 까지 하시고 Android, iOS, Windows 중 하나를 시작 프로젝트로 설정 후 실행해보시면
버튼 2개가 생성되었음을 확인 하실 수 있습니다! 잘 따라 오셨나요?

As you guys can see /ContentPage, all of above the are one thing in MainPage.xaml.
If you execute it, you can see two buttons. So far so good?


자, 2단계인 새 페이지 추가하기입니다.
맨 위에부분에 마우스 오른쪽 클릭하여 새 항목 추가 후 Forms Xaml Page 하나 추가합니다.
저는 이름을 NewPage.xaml라고 지정하였습니다.

OK, here is step 2.
Add a Form Xaml Page by right clicking SeminarExample(Portable)
My page title is NewPage.xaml.


새 페이지 추가해서 이동하기만 확인할 거라서 따로 레이아웃은 안나누었습니다.
Hi라는 글자를 확인 하기 위해 Label이라는 내용을 NewPage.xaml에 추가하였습니다.

We don't have to divide this layout because I'll just check the new page out.
Add the following code to display "Hi" in NewPage.xaml.

 
<?xml version="1.0" encoding="utf-8" ?>
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SeminarExample.NewPage"
             Title ="I'm a new page">

    <Label Text="Hi"
           FontSize="30"
           VerticalOptions="Center"
           HorizontalOptions="Center"
           />
</ContentPage>


원하는 동작은 아까 처음에 만들었던 두개의 버튼 중 위에 버튼(NEW PAGE)라는 버튼을 눌렀을 때
새로 만든 페이지로 이동하는 동작입니다.
그러기 위해선 만들었던 버튼에 기능을 구현해주어야 하는데요.
기능 담당은 주로 .cs확장자에서 합니다.
MainPage.xaml.cs로 이동하여서
간단하게 몇줄로 생명을 불어넣어봅시다!

To move the new page, we have to design it.
(When someone wants to add some functions, more often than not, we usually use this file which is named .cs)
After we go to MaiinPage.xaml.cs, copy and paste the following code.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace SeminarExample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();

            AddPageBtn.Clicked += async (sender, e) =>
            {
                await Navigation.PushAsync(new NewPage());
            };
        }
    }
}

버튼이름.Clicked += async (sender, e) 이런 형식이니
버튼 이름을 지정해주셔야 합니다.
아까 MainPage.xaml에 Button 생성시 x:Name="AddPageBtn" 이런식입니다.
Navigation.PushAsync(new 요기) 요기에는 이동할 페이지의 이름을 써주시면 됩니다.
우리는 NewPage.xaml로 생성하셨으니 NewPage라고 쓰면 됩니다.

Button name.Clicked += async(sender, e). This is the form.
Thus, we have to decide buttons' names.
When we created the buttons in MainPage.xaml, we can see x:Name="AddPageBtn".
Navigation.PushAsyhc(new Here). Here is the page's name.
Hence, our new page's name is NewPage.xaml. just write (new NewPage).


여기까지 따라 오신 뒤, 실행하시면 위에 NEW PAGE를 누르셨을때
생성한 NewPage.xaml로 이동함을 확인 할 수 있습니다.

If you execute your project, you can move to New Page.xaml and see "Hi".


이번엔 앞에 2가지를 응용해서
버튼클릭->새 페이지 이동->웹뷰 띄우기를 할건데요.
 
우선 다시 오른쪽 클릭하셔서 새항목 추가 Forms Xaml Page로 하시면 됩니다.
저는 GoogleWebViewPage.xaml로 하였습니다.
 
GoogleWebViewPage.xaml.cs에 이 소스코드를 추가하시면 됩니다.
(GoogleWebViewPage.xaml에는 별도 추가 아무것도 안하셔도 됩니다.)

Finally, I'll use two things of the above.
The order is clicking buttons -> moving new page -> displaying web view.

First of all, add a Forms Xaml Page by right clicking SeminarExample(Portable)
My new page title is GoogleWebViewPage.xaml.

Copy and paste the following code in GoogleWebViewPage.xaml.cs.
(You guys don't have to write anything in GoogleWebViewPage.xaml)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;

namespace SeminarExample
{
    public partial class GoogleWebView : ContentPage
    {
        public GoogleWebView()
        {
            InitializeComponent();

            Label header = new Label
            {
                Text = "용범이가 만든 웹뷰",
                FontSize = 20,
                FontAttributes = FontAttributes.Bold,
                HorizontalOptions = LayoutOptions.Center
            };

            WebView webView = new WebView
            {
                Source = "http://google.com",
                VerticalOptions = LayoutOptions.FillAndExpand,
                HorizontalOptions = LayoutOptions.FillAndExpand
            };
            
            this.Content = new StackLayout
            {
                Children =
                {
                    header,
                    webView
                }
            };
        }
    }
}

 Source = " " 이 부분에 웹뷰로 띄우고 싶은 URL주소를 적으시면 됩니다.
In this part, Source = " ", write the URL address you want to display.



 
요 전에 했던과 방식과 같이 MainPage.xaml.cs에서
AddPageBtn.Clicked += async (sender, e) 밑에

Like we have done in MainPage.xaml.cs, after AddPageBtn.Clicked += async (sender, e), 
 
GoogleBtn.Clicked += async (sender, e) =>
            {
                await Navigation.PushAsync(new GoogleWebView());
            };

요걸 추가해주세요. 저는 이름을 GoogleWebView.xaml로 새 페이지를 생성하였고
밑에 구글버튼을 x:Name="GoogleBtn"으로 하였기에 저런 형식이 나온겁니다.

Write the code.
I don't only write (new Google Webview()); because new page title is GoogleWebView.xaml,
but also write GoogleBtn.Clicked += async (sender, e) because my button's name is GoogleBtn.


 짠! 밑에 Google.com이라 써있는 버튼을 누르시면 새 페이지로 이동 후, 
웹뷰로 구글이 뜨는 것을 확인 할 수 있습니다.
잘 따라오셨나요?!
개인적으로 질문 있으시다면 댓글 남겨주세요!
그러면 오늘 하루도 좋은하루 되세요^^

Holy moly! After you click the Google.com button, could you see the Google web page?
Well done! If you have trouble in it, type a comment! I want to help people who need my help if I can.
Have a good day, good luck :) 


'컴퓨터공학 > 자마린(Xamarin)' 카테고리의 다른 글

1. 자마린 소개 및 설치방법  (0) 2017.06.30

BE THE FIRST PENGUIN