관리 메뉴

java,javascript,android,php,sql,공부용,메모용

안드로이드 미션4 문자화면 / Android Studio / 안드로이드 앱만들기 공부 본문

모바일/안드로이드앱

안드로이드 미션4 문자화면 / Android Studio / 안드로이드 앱만들기 공부

yy_dd2 2021. 3. 6. 06:57
반응형

책에서 미션4로 내준 문제가 기존의 내용가지고는 풀기가 어렵다.

그리고 모르는 내용이 있어서 코드를 참고해서 내용을 확인해봤다.

github.com/young-0112/MissionLayout4

 

여기서 확인 할 것

- Layout 정렬방법

- 몇글자 작성했는지 확인하기

- 모르는 메서드 확인 및 메모

 

최종적으로 만들 레이아웃 상태

 

 

 

1. 기본적인 레이아웃을 살펴보면

- 상대레이아웃을 최상위 레이아웃을둔다

- 그아래 상대레이아웃안에 EditText 추가 TextView 추가

- 가로 정렬을 위해서 LinearLayout 2개 추가 vartical / horizontal

- 기본적인 margin이나 padding이 없는 상태다

- 그리고 상대레이아웃의 속성을 사용해서 각각에 연결해주었다

 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/inputlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/buttonLayout"
        android:layout_alignParentTop="true">

        <EditText
            android:id="@+id/inputMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/inputCount"
            android:layout_alignParentTop="true"
            android:gravity="top"
            android:maxLength="80"
            android:text="" />

        <TextView
            android:id="@+id/inputCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:text="0 / 80 바이트"
            android:textColor="#FF5722" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

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

            <Button
                android:id="@+id/sendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="전송"
                android:textSize="18sp" />

            <Button
                android:id="@+id/closeButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="닫기"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>


</RelativeLayout>

- 최상위 레이아웃은 그대로 있다

- 첫번째 RelativeLayout은 layout_above 속성으로 2번째 LinearLayout (id = buttonLayout)보다 위에 있게 설정

    <RelativeLayout
        android:id="@+id/inputlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/buttonLayout"
        android:layout_alignParentTop="true">

 

 

- EditText를 TextView보다 위에있게 설정

- EditText를 부모컨테이너와 위쪽을 나란히 맞춤 (맨위로 붙게)

- gravity를 이용해서 중간왼쪽부터 나오는 글을 맨위에서 나오도록 top지정 (gravity : 내용물 정렬 속성)

- android:maxLength="80" 배우지 않은 속성이다 maxLength는 최대길이를 지정하는 속성이다

 

        <EditText
            android:id="@+id/inputMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/inputCount"
            android:layout_alignParentTop="true"
            android:gravity="top"
            android:maxLength="80"
            android:text="" />

        <TextView
            android:id="@+id/inputCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:text="0 / 80 바이트"
            android:textColor="#FF5722" />

 

- 상대 레이아웃 RelativeLayout :규칙(Rule) 기반 모델 / 부모 컨테이너나 다른 뷰와의 상대적 위치로 화면을 구성하는 방법 / 제약 레이아웃을 사용하게 되면서 상대 레이아웃은 권장하지 않음
출처: https://tog-code.tistory.com/12 [java,javascript,android,php,sql,공부용,메모용]

 

상대 레이아웃 RelativeLayot  속성정리

속성 설명
layout_alignParentTop 부모 컨테이너의 위쪽과 뷰의 위쪽을 맞춤
layout_alignParentBottom 부모 컨테이너의 아래쪽과 뷰의 아래쪽을 맞춤
layout_alignParentLeft 부모 컨테이너의 왼쪽 끝과 뷰의 왼쪽 끝을 맞춤
layout_alignParentRight 부모 컨테이너의 오른쪽 끝과 뷰의 오른쪽 끝을 맞춤
layout_centerHorizontal 부모 컨테이너의 수평 방향 중앙에 배치
layout_centerVerical 부모 컨테이너의 수직 방향 중앙에 배치
layout_centerInParent 부모 컨테이너의 수평과 수직 방향 중앙에 배치

상대 레이아웃에서 부모 컨테이너와의 상대적 위치를 이용하는 속성

 

부모 컨테이너가 아닌 다른 뷰와의 상대적 위치를 이용해 뷰를 배치할 수 있는 속성은 아래와 같다

속성 설명
 layout_above 지정한 뷰의 위쪽에 배치
 layout_below 지정한 뷰의 아래쪽에 배치
 layout_toLeftOf 지정한 뷰의 왼쪽에 배치
 layout_toRihtOf 지정한 뷰의 오른쪽에 배치
 layout_alignTop 지정한 뷰의 오른쪽에 배치
 layout_alignBottom
지정한 뷰의 내용물의 기준선을 맞춤

출처: https://tog-code.tistory.com/12?category=412339 [java,javascript,android,php,sql,공부용,메모용]

 

- 버튼 레이아웃은 LinearLayout 두개로 정렬을 해준다 vertical, horizontal가로정령세로정렬해준다

- 두번째 리니어 레이아웃에 android:layout_gravity="center_horizontal"은 중앙으로 가게해준다

 

    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

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

            <Button
                android:id="@+id/sendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="전송"
                android:textSize="18sp" />

            <Button
                android:id="@+id/closeButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="닫기"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>

 


 

2. 이제 여기서 margin과 padding을 주고 모양을 예쁘게 다듬습니다.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <RelativeLayout
        android:id="@+id/inputlayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/buttonLayout"
        android:layout_alignParentTop="true">

        <EditText
            android:id="@+id/inputMessage"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/inputCount"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:gravity="top"
            android:maxLength="80"
            android:text="" />

        <TextView
            android:id="@+id/inputCount"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="30dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:text="0 / 80 바이트"
            android:textColor="#FF5722" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/buttonLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical">

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

            <Button
                android:id="@+id/sendButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:text="전송"
                android:textSize="18sp" />

            <Button
                android:id="@+id/closeButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:paddingLeft="20dp"
                android:paddingRight="20dp"
                android:text="닫기"
                android:textSize="18sp" />
        </LinearLayout>
    </LinearLayout>


</RelativeLayout>

 

두개는 같은 이미지

 


이번에 MainActivity.java에서 할게 많다

 

자세한 내용은 주석참고

 

 

 

 

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.UnsupportedEncodingException;


public class MainActivity extends AppCompatActivity {

    EditText inputMessage;
    TextView inputCount;

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

        // activity_main.xml 에서 찾아오기
        inputMessage = findViewById(R.id.inputMessage);
        inputCount = findViewById(R.id.inputCount);

        // activity_main.xml에서 전송 버튼 찾아오기
        Button sendButton = findViewById(R.id.sendButton);
        // sendButton에 클릭 이벤트 설정하기
        // activity_main.xml의 sendButton에 클릭이벤트 setOnClickListener(new View.OnClickListener(){})
        // inputMessage 안에 있는 텍스트 가져오기
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = inputMessage.getText().toString();
                // sendButton을 누르면 전송할 메시지가 뜨도록 설정
                // - getApplicationContext() : 액티비티를 참조할 수 없는 경우 getApplicationContext() 메서드를 호출하면 Context 객체가 반환됩니다.
                Toast.makeText(getApplicationContext(), "전송할 메시지\n\n" + message, Toast.LENGTH_LONG).show();
            }
        });

        // activity_main.xml에서 닫기 버튼 찾아오기
        Button closeButton = findViewById(R.id.closeButton);
        // closeButton 에도 이벤트 설정하기
        closeButton.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                // 액티비티 종료
                finish();
            }
        });

        // - TextWatcher 객체 텍스트가 변경될 때마다 발생하는 이벤트 처리
        // 텍스트 변경 전/시/후
        TextWatcher textWatcher = new TextWatcher() {

            //텍스트가 입력될때마다 텍스트 숫자를 세어준다.
            @Override
            public void beforeTextChanged(CharSequence str, int start, int before, int count) {
            //public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                // String[] 문자 배열 byte 기본값 0
                // String 문자열 원하는 인코딩으로 변환 검색키워드 String 인코딩, 자바 파라미터 인코딩
                //
                byte[] bytes = null;
                try {
                    // 바이트로 리턴받기
                    // KSC5601은 안드로이드에서 한글을 byte로 변환하는 방식이라고 한다.
                    bytes = str.toString().getBytes("KSC5601");
                    // 배열에 저장된 길이값 가져오기
                    int strCount = bytes.length;
                    // 가져온 길이값은 inputCount라는 TextView에 나타내기
                    inputCount.setText(strCount + " / 80바이트");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            //텍스트가 입력된후에 정해진 글자수보다 초과했을때 잘라서 넣어준다.
            @Override
            public void afterTextChanged(Editable strEditable) {
                // 입력된 모든 문자
                String str = strEditable.toString();
                try {
                    // 바이트로 리턴아서 배열에저장
                    byte[] strBytes = str.getBytes("KSC5601");
                    if(strBytes.length > 80){
                        strEditable.delete(strEditable.length()-2, strEditable.length()-1);
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        };

        inputMessage.addTextChangedListener(textWatcher);


    }

}

 

기억하기

// - getApplicationContext() : 액티비티를 참조할 수 없는 경우 getApplicationContext() 메서드를 호출하면 Context 객체가 반환됩니다.

Toast.makeText(getApplicationContext(), "전송할 메시지\n\n" + message, Toast.LENGTH_LONG).show();

 

// 액티비티 종료
finish();

 

// - TextWatcher 객체 텍스트가 변경될 때마다 발생하는 이벤트 처리

TextWatcher textWatcher = new TextWatcher() {

//텍스트가 입력될때마다 텍스트 숫자를 세어준다.

@Override
public void beforeTextChanged(CharSequence str, int start, int before, int count) {

// String[] 문자 배열 byte 기본값 0

// String 문자열 원하는 인코딩으로 변환 검색키워드 String 인코딩, 자바 파라미터 인코딩

// 바이트로 리턴받기

bytes = str.toString().getBytes("KSC5601");

// KSC5601은 안드로이드에서 한글을 byte로 변환하는 방식이라고 한다.

 

 

//텍스트가 입력된후에 정해진 글자수보다 초과했을때 잘라서 넣어준다.

@Override
public void afterTextChanged(Editable strEditable) {

 

아래 코드 내용이 잘라서 넣어주는 내용인거 같은데 이부분 이해를 잘못했다 다음에 검색해서

다시 찾는다면 확인해야할거같다. 메모

if(strBytes.length > 80){
strEditable.delete(strEditable.length()-2, strEditable.length()-1);
}

반응형
Comments