안드로이드 프로그램에서 제일 많이 사용하게 되는 View 인터페이스 TextView EditText 이용하여 엔터키 이벤트 사용 방법을 알아 봅니다

엔터키 이벤트는 EditText에서 발생 하는데 여러가지 key event 들이 발생 하면 그중 enter event 선택하여 처리를 하는 것으로 2가지 방법을 이용하게 됩니다. 하나는 EditText 생성시 직접 이벤트 처리를 부여하는 방법이고 다른 하나는 implements 사용하여 OnKeyListener 상속받아 처리하는 방법 입니다최종 구현 상태는 아래 그림과 같습니다.


android enter key



1. 프로젝트 생성


실제로 프로젝트를 생성해 보도록 하겠습니다.


android enter key


Empty Activity 선택 하고


android enter key

 

적당한 프로젝트 명을 입력 합니다신규로 추가하는 프로그램 없이 프로젝트 생성시 기본적으로 생성되는 파일을 이용하여 구현합니다.

 

2. Layout 구현

 

먼저 activity_main.xml파일에 EditText 2 추가해 줍니다. id 적당히 입력을 해주면 됩니다하나는 생성할때 이벤트 처리 기능을 부여 하고 다른 하나는 OnKeyListener 이용한 처리에 사용하게 됩니다.

<TextView

        android:id="@+id/plain_text"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="hello world"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintLeft_toLeftOf="parent"

        app:layout_constraintRight_toRightOf="parent"

        app:layout_constraintTop_toTopOf="parent" />

 

    <EditText

        android:id="@+id/plain_text_input"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="112dp"

        android:hint="text1"

        android:inputType="text"

        app:layout_constraintTop_toTopOf="parent"

        tools:layout_editor_absoluteX="27dp" />

 

    <EditText

        android:id="@+id/plain_text_input2"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:layout_marginTop="168dp"

        android:hint="text2"

        android:inputType="text"

        app:layout_constraintTop_toTopOf="parent"

        tools:layout_editor_absoluteX="0dp" />

 

 

3. Java 기능 구현

 

MainActivity.java 에서 이벤트 처리 로직입니다.


3.1 첫번째 이벤트 처리 방법


첫번째는 onCreate()에서 EditText 생성할 엔터 이벤트 처리 로직을 부여하는 방법 입니다. EditText 생성 하고 바로 onKey() 기능을 추가하여  필요한 작업을 구현하면 됩니다.

@Override

    protected void onCreate(Bundle savedInstanceState) {

eText2 = (EditText) findViewById(R.id.plain_text_input2);

 

eText2.setOnKeyListener(new View.OnKeyListener() {

            @Override

            public boolean onKey(View v, int keyCode, KeyEvent event) {

                switch (keyCode) {

                    case KeyEvent.KEYCODE_ENTER:

                        txtView.setText(eText2.getText());

                        break;

                }

                return true;

            }

        });

}

 

구현된 작업은 EditText 입력한 내용을 TextView 출력 하게 하는 간단한 작업 입니다.

 

3.2 두번째 이벤트 처리 방법


두번째는 OnKeyListener 상속받아 onKey() 구현하는 방법 입니다. class implements OnKeyListener 상속하고 Override onKey() 구현을 하면 됩니다.

public class MainActivity extends AppCompatActivity implements View.OnKeyListener {

 

@Override

protected void onCreate(Bundle savedInstanceState) {

eText1 = (EditText) findViewById(R.id.plain_text_input);

    eText2 = (EditText) findViewById(R.id.plain_text_input2);

}

 

@Override

public boolean onKey(View v, int keyCode, KeyEvent event) {

         if(keyCode == KeyEvent.KEYCODE_ENTER) {

            switch (v.getId()) {

                case R.id.plain_text_input:

                    txtView.setText(eText1.getText());

                    break;

                case R.id.plain_text_input2:

                    txtView.setText(eText2.getText());

                    break;

            }

            return true;

        }

        return false;

}

 

구현된 내용은 EditText에서 이벤트를 받으면 엔터 이벤인가 확인 하고 2개의 EditText 어디에서 발생 하였는지 확인하여 입력한 내용을 TextView 출력 하게 하는 작업 입니다.

 


android enter key

위에 있는 결과는 두번째 EditText에서 엔터키 이벤트가 발생한것을 있습니다.

 

4. 전체 Source


4.1 activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
   
xmlns:app="http://schemas.android.com/apk/res-auto"
   
xmlns:tools="http://schemas.android.com/tools"
   
android:layout_width="match_parent"
   
android:layout_height="match_parent"
   
tools:context=".MainActivity">

    <TextView
       
android:id="@+id/plain_text"
       
android:layout_width="wrap_content"
       
android:layout_height="wrap_content"
       
android:text="hello world"
       
app:layout_constraintBottom_toBottomOf="parent"
       
app:layout_constraintLeft_toLeftOf="parent"
       
app:layout_constraintRight_toRightOf="parent"
       
app:layout_constraintTop_toTopOf="parent" />

    <EditText
       
android:id="@+id/plain_text_input"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="112dp"
       
android:hint="text1"
       
android:inputType="text"
       
app:layout_constraintTop_toTopOf="parent"
       
tools:layout_editor_absoluteX="27dp" />

    <EditText
       
android:id="@+id/plain_text_input2"
       
android:layout_width="match_parent"
       
android:layout_height="wrap_content"
       
android:layout_marginTop="168dp"
       
android:hint="text2"
       
android:inputType="text"
       
app:layout_constraintTop_toTopOf="parent"
       
tools:layout_editor_absoluteX="0dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

4.2MainAcitivity.java


두가지 기능을 한곳에 담아 보았습니다.

package copycoding.tistory.texttest;

import
androidx.appcompat.app.AppCompatActivity;

import
android.os.Bundle;
import
android.view.KeyEvent;
import
android.view.View;
import
android.widget.EditText;
import
android.widget.TextView;

public class
MainActivity extends AppCompatActivity implements View.OnKeyListener {
    EditText
eText1, eText2;
   
TextView txtView;
   
@Override
   
protected void onCreate(Bundle savedInstanceState) {
       
super.onCreate(savedInstanceState);
       
setContentView(R.layout.activity_main);

       
eText1 = (EditText) findViewById(R.id.plain_text_input);
       
eText2 = (EditText) findViewById(R.id.plain_text_input2);
       
txtView = (TextView) findViewById(R.id.plain_text);
       
eText1.setOnKeyListener(this);
       
eText2.setOnKeyListener(new View.OnKeyListener() {
           
@Override
           
public boolean onKey(View v, int keyCode, KeyEvent event) {
               
switch (keyCode) {
                   
case KeyEvent.KEYCODE_ENTER:
                       
txtView.setText(eText2.getText());
                        break;
               
}
               
return true;
           
}
        })
;
   
}

   
@Override
   
public boolean onKey(View v, int keyCode, KeyEvent event) {
        
if(keyCode == KeyEvent.KEYCODE_ENTER) {
           
switch (v.getId()) {
               
case R.id.plain_text_input:
                   
txtView.setText(eText1.getText());
                    break;
//                case R.id.plain_text_input2:
//                    txtView.setText(eText2.getText());
//                    break;
           
}
           
return true;
       
}
       
return false;
   
}
}

 

- copy coding - 



로그파일, xml등 프로그램을 하다보면 텍스트 문서를 불러왔는데 모두 한 줄로 이어져 있어 읽어 보기가 매우 힘든 경우가 있는데 공통된 반복 문구를 이용하여 줄바꿈(라인피드, 개행)하는 방법입니다알면 쉽고 모르면 한동안 방법을 찾아서 시간을 낭비해야 하는 경우가 있어 정리를 해봅니다.


editplus 줄바꿈


위와 같이 xml 파일이 모두 한 줄로 되어 있어 구조를 파악하기 상당히 힘든 경우에 “><” 이 중간 부분에 줄바꿈을 넣는다면 가독성이 좋아지겠죠.

그럼 우리가 기본적으로 생각하는 방법으로 바꾸기 명령을 이용하여 변경을 해 봅니다.

 

메뉴에서

검색 > 바꾸기

또는 단축 키

Ctrl + H

를 하여 바꾸기 창을 열고


editplus 줄바꿈


><>\n<으로 모두 바꿈 버튼을 클릭 해 봅니다.

 

안타깝지만 줄바꿈이 되지 않고 문장에 “\n”이 추가되어 있습니다.


editplus 줄바꿈


이렇게 특수 기호를 이용한 바꾸기를 하는 경우에는


editplus 줄바꿈


그림과 같이 정규식 항목을 체크하고 작업을 해야 합니다.

다시 한번 모두 바꿈 버튼을 클릭 합니다.


editplus 줄바꿈


원하는 줄바꿈 작업이 완료 되었습니다. 어떤 내용인지 편하게 볼 수 있게 되었습니다.


- copy coding -


안드로이드 스튜디오를 처음 설치할 때 배경에 대한 테마를 선택하도록 되어 있습니다하얀 바탕과 검은 바탕 중 어떤걸 선택 할지 조금 고민을 하게 되는데 대부분 기본으로 설정되어 있는 검은 색의 Darcula를 선택하고 넘어 갑니다.

그런데 코딩을 하다 보면 환경에 따라 또는 기호에 따라 하얀색 바탕이 편할 때도 있습니다개인적으로는 낮에는 검은 배경, 밤에는 하얀색 배경이 글씨를 보는데 눈의 피로를 덜 하게 되는 것 같습니다. 현재는 Darcula로 설정이 되어 있습니다.


android theme


테마 설정 변경은 간단합니다메뉴에서


 File > Settings...


를 선택 하면 


android theme


Settings 팝업 창이 나타나고


android theme


좌측 메뉴에서


Appearance & Behavior > Appearance


를 찾아서 클릭 합니다. 이제 우측 첫 번째 항목에

Theme:를 확장해 주면 Darcula, High contrast, IntelliJ 중 하나를 선택 할 수 있습니다.

 

먼저 High contrast를 선택하고 하단에 있는 OK 버튼을 클릭해 봅니다.


android theme


밋밋하던 개발 환경이 조금 강렬해 졌습니다. 대신 눈은 피곤해질것 같네요.


다시 Settings 창을 열고


android theme


이번에는 IntelliJ 를 선택 하고 OK 버튼을 클릭 합니다.


android theme


흰색 바탕의 편집 모드로 변경이 되었습니다

각자 눈의 피로가 덜 할 수 있는 테마를 골라서 사용해 보세요.


- copy coding -


논리적 개념을 도식화 하기에 좋은 Graphviz anaconda에 설치하고 python언어를 이용하여 프로그램을 만들고 jupyter에서 간단한 예제를 해보려고 합니다.

아나콘다 설치는 매우 간단 해서 설명이 필요 없지만 한번 훑어보려면 아래 링크에서 아나콘다 부분만 보시면 됩니다.


[텐서플로우] 아나콘다(Anaconda)에 TensorFlow2 설치


그럼 아나콘다는 설치가 되어 있다고 치고 graphviz 설치를 시작해 봅니다.

 

Windows 7Graphviz 설치 방법


python graphviz install


먼저 시작버튼을 눌러 Anaconda Prompt를 실행하고 설치 명령어를 입력 합니다.

 

conda install graphviz

 

명령어를 입력하고 나면 잠시 후 설치하려는 프로그램 목록이 나타납니다기존에 파이선이 업데이트가 되어 있다면 설치할 package 개수가 적을 수도 있습니다.


python graphviz install




python graphviz install


진행 여부를 물어보면 y를 입력하거나 [y]가 선택되어 있으니 그냥 엔터를 처도 됩니다.


python graphviz install


기다리다 보면 설치가 완료 되었습니다.

 

conda 명령말고 pip를 이용해서 설치도 가능한데


pip install graphviz


명령어로도 설치할 수 있습니다.


python graphviz install


 

이미 설치되어 있다고 나오는군요.

 

간단한 예제를 하나 해보도록 하겠습니다. 기본적인 원형 도표를 만들고 png 이미지 파일을 만드는 프로그램 입니다.

 

from graphviz import Source

 

dot_digraph = """

digraph graphname {

    rankdir=LR;

     a -> b -> c -> e ->f;

     b -> d;

}

"""

s = Source(dot_digraph, filename='simple_digraph', format='png')

s.view()

 

그런데 프로그램을 실행하면 오류가 발생 합니다.


python graphviz install


graphviz는 설치하고 Path를 잡아줘야 합니다. 어디에 설치가 되었는지 설치 위치를 찾아야 설정을 하겠죠. graphviz 설치 위치는 아나콘다를 어디에 설치 했는가에 따라 폴더가 달라집니다. 저의 경우는


C:\ProgramData\Anaconda3\Library\bin\graphviz


요기에 설치가 되어 있습니다그럼 속성 항목에 path를 선택 해서 추가를 해 줍니다추가하는 방법은 변수 값 항목 제일 뒤에 세미콜론(;)을 추가하고 폴더 위치를 추가해 주면 됩니다.


;C:\ProgramData\Anaconda3\Library\bin\graphviz


python graphviz install


열린 시스템 속성 변수 창들을 [확인]버튼을 눌러 모두 닫아주면 시스템에 설정이 반영 됩니다그러나 이미 열려있는 jupyter notebook은 설정 값이 적용되어 있지 않는 상태 입니다새로 추가한 설정이 반영 되도록 jupyter noteboot을 종료 하고 다시 켜서 프로그램을 실행해 봅니다.


python graphviz install


잘 나오는 군요성공 입니다.

 

 

Windows 10Graphviz 설치 방법

 

Windows 10에서도 동일한 방법으로 설치와 테스트가 가능 합니다Windows 7과 방법이 동일해서 좀 성의 없이 요점만 설명을 하도록 하겠습니다.

 

Anaconda Prompt를 실행하고 설치 명령어를 입력 합니다.

 

conda install graphviz 


python graphviz install


pip 명령으로도 설치가 가능 하고요


pip install graphviz


python graphviz install


설치가 완료 되면 anaconda의 설치 위치를 알면 graphviz의 설치 위치도 찾을 수 있습니다.


C:\anaconda3\Library\bin\graphviz


python graphviz install


저는 이곳에 설치가 되어 있습니다.  환경 변수 path에 위치를 추가해 줍니다.


python graphviz install


설정 값을 반영하기 위해 주피터 노트북 창을 닫고 재시작 하여 프로그램을 시작해 봅니다.


python graphviz install


당연히 윈도우10에서도 잘 실행이 됩니다.


- copy coding -


1···29303132333435···118

+ Recent posts