1. 로그인 액티비티 생성


안드로이드에서 기본적으로 로그인 폼을 지원한다. Activity 추가시 Login Activity 를 생성한다.


Activity Name과 레이아웃 xml 파일 이름, 타이틀 이름을 입력하고 Finish 버튼을 눌러서 생성한다.


2. 레이아웃 구조 수정


res-> layout -> activity_login.xml 파일을 보면 현재 페이지의 레이아웃이 어떻게 구성되어지는지 볼 수 있다. 여기서 필요한 요소를 추가하거나 삭제할 수 있다. Component Tree 탭을 활용하면 현재 레이아웃 계층이 어떻게 구성되어 있는지 한눈에 알아 볼 수 있다.

로그인 폼이 어떻게 만들어 졌는지 살펴 보면 Linear Layout(Horizontal) -> Scroll View -> Linear Layout(Vertical) 안에 EditText, Button 등이 차례로 들어가져 있는 모습을 볼 수 있다. Scroll View는 필요 없을 것 같아 삭제하고 구조를 Linear Layout(Horizontal) -> LinearLayout(Vertical) -> EditText, EditText, Button, Button 구조로 수정하였다.


안드로이드 어플리케이션의 화면을 구성할 때 버튼이나 텍스트 뷰, 텍스트입력, 버튼 등 각 요소를 넣으려면 Layout 안에 넣어줘야 어느 화면에서나 구조적으로 배치가 될 수 있다. 여기서는 LinearLayout이 Layout 컴포넌트에 해당이 된다. Layout 구조는 아래의 그림과 같이 다양하게 구성되어 있다. 구현시 원하는 기능대로 레이아웃을 추가하여 레이아웃 안에 컴포넌트를 추가하면 된다.



res-> layout -> activity_login.xml 파일을 보면 레이아웃 구조를 Text로 변경해서 보면 각 요소별로 설정을 할 수 있다. id는 해당 컴포넌트를 구별하기 위하여 이름을 지어두는 곳이고, layout_width, layout_height 는 해당 컴포넌트의 가로, 세로 길이를 결정한다.


match_parent 는 쉽게 말하면 부모 컴포넌트의 가로나 세로 길이에 맞춰서 해당 컴포넌트의 길이를 설정하라는 뜻이다. 레이아웃 뷰에서 Linear Layout의 가로 길이를 화면의 가로 길이만큼(match_parent)으로 설정 했기 때문에 button의 width(가로)를 match_parent로 설정했을때 가로 길이가 화면에 꽉차게 보이는 것이다.


wrap_content 는 해당 뷰에 들어있는 내용물의 크기에 따라 뷰의 크기가 결정되도록 조정한다. 즉, 컴포넌트에 텍스트가 존재하면 텍스트의 크기 만큼 컴포넌트의 크기가 결정되는 것이다.


margin 은 컴포넌트와 컴포넌트 사이의 간격(바깥 여백)을 지정하는 것이고, padding 은 컴포넌트에 할당된 뷰 내부(안쪽 여백)에서 크기를 조절 할 때 사용한다.

아래의 로그인과 회원가입 버튼처럼 버튼을 한 행에 배치 할 때는 LinearLayout(horizontal)을 추가한 뒤 버튼 2개를 레이아웃 안에 추가해주면된다. 버튼의 길이를 결정할 때 임의의 값을 지정해주게 되면 화면 크기에 따라서 다르게 보이기때문에 weight 라는 속성을 이용하여 지정하였다. 로그인 버튼과 회원가입 버튼의 weight를 1 로 지정했기 때문에 한 행에서 동일한 길이의 버튼이 생성되었다.
만약, 로그인 버튼의 weight를 2, 회원가입 버튼의 weight를 1로 지정하였다면 로그인의 버튼이 회원가입 버튼보다 상대적으로 길이가 길 것이다. (weight 2는 전체 길이의 2/3, weight 1은 전체 길이의 1/3)

  • weight가 1:1 인 경우


  • weight가 2:1 인 경우


수정한 폼과 코드는 아래와 같다.


  • activity_login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.devyurim.orangeaid.LoginActivity">

    <LinearLayout
        android:id="@+id/email_login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical">

        <EditText
            android:id="@+id/email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/prompt_email"
            android:inputType="textEmailAddress"
            android:maxLines="1"
            android:singleLine="true" />

        <EditText
            android:id="@+id/password"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/prompt_password"
            android:imeActionId="6"
            android:imeActionLabel="@string/action_sign_in"
            android:imeOptions="actionUnspecified"
            android:inputType="textPassword"
            android:maxLines="1"
            android:singleLine="true" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <Button
                android:id="@+id/email_sign_in_button"
                style="?android:textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:layout_weight="1"
                android:text="@string/action_sign_in"
                android:textStyle="bold" />

            <Button
                android:id="@+id/email_sign_up_button"
                style="?android:textAppearanceSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:layout_weight="1"
                android:text="@string/action_sign_up"
                android:textStyle="bold" />
        </LinearLayout>

    </LinearLayout>
</LinearLayout>


3. 컴포넌트 텍스트 수정


res -> values ->strings.xml 파일에 가보면 로그인 폼에서 사용되는 string 변수들이 자동으로 생성되어 있다. 여기서 원하는 텍스트로 수정해주면 된다.
(text view 글자, hint 글자, button 글자, page title 등)
추가 문구가 필요하면 생성하고 컴포넌트에 매칭시켜주면 된다. 필요한 사항만 남기고 나머지는 모두 지웠다. 필요 할때마다 추가하여 사용한다.

layout_login.xml에 가보면 text 요소에 “@string/action_sign_in”라고 기재되어 있다. 이 코드의 의미는 strings.xml의 name이 action_sign_in인 문구를 사용하라는 뜻이다. 통일성을 위해서 나는 strings.xml 파일을 사용하여 텍스트 값을 변경하였다.


추가적으로 화면의 타이틀을 변경하고 싶으면 AndroidManifest.xml 파일에서 해당 액티비티의 label 값을 수정해주면 된다.



4. LonginActivity.java 수정


로그인 액티비티를 생성하면 로그인 기능에 사용되는 기본적인 함수들이 자동으로 생성이 되므로 나중에 기능을 추가할 때 문서를 보고 함수를 수정하면 된다. 아직 서버가 완성되지 않았으므로 일단은 onCreate 함수 빼고 모두 지워 주었다. 필요한 기능이 생길때 마다 그때 함수를 추가하는 방식으로 작성할 예정이다. 또한, EditText나 Button에서 각각 이벤트 핸들러를 적용할 수 있도록 이벤트 핸들러 함수를 추가하였다.

또한, 이메일 입력 자동완성기능은 DB와 연동이 필요하기 때문에 AutocompleteTextView에서 textedit로 컴포넌트를 변경해 주었다.

수정한 코드는 아래와 같다.

  • LoginActivity.java


import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class LoginActivity extends Activity {

    // UI references.

    private EditText mEmailView;
    private EditText mPasswordView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // Set up the login form.

        mEmailView = (EditText) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);

        // event handler

        mEmailView.setOnEditorActionListener(new TextView.OnEditorActionListener()
        {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if(id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL){
                   return true;
                }
                return false;
            }

        });
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    //attemptLogin();

                    return true;
                }
                return false;
            }
        });

        // Button

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); // sign in button

        Button mEmailSignUpButton = (Button) findViewById(R.id.email_sign_up_button); // sign up button


        // event handler

        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        mEmailSignUpButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {

            }
        });

    }

}



아직 서버가 연동되지 않았으므로 각 버튼을 눌렀을 시 다른 액티비티로 넘어가도록 구현 하였다. 로그인 버튼을 눌렀을 때 MainActivity 로 넘어가고 회원가입 버튼을 눌렀을때 RegisterActivity 로 넘어가도록 핸들러를 구현하였다.

일단 RegisterActivity를 Empty Activity로 추가 해준다음 다음과 같이 코드를 수정하였다.

// sign-in button event handler

        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                startActivity(intent);
                finish();

            }
        });

        // sign-up button event handler

        mEmailSignUpButton.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
                startActivity(intent);
                finish();
            }
        });



추후 웹 서버 연동과 db연동을 한 후 로그인 확인기능과 추가 핸들러 기능을 구현할 예정이다.위의 예제 코드로 왠만한 기본적인 안드로이드 페이지를 응용하여 만들수 있다.(회원가입 폼, 기본 메뉴 화면 등) 어플리케이션에 필요한 화면들을 다 만든 뒤 추가 기능을 추가해야겠다.