포스팅 OS : Mac

검색어 : 안드로이드(Android), 코틀린(Kotlin), 텍스트뷰(TextView), 버튼(Button)




▶︎ 이전 포스팅 목록

2018/02/10 - [Android_Kotlin] - [Android Kotlin] 안드로이드 스튜디오(Andorid Studio)에 코틀린(Kotlin) 개발환경 셋팅



이전 포스팅에서는 안드로이드 스튜디오에 코틀린 개발환경을 셋팅하는 방법에 대해 알아보았습니다. 오늘은 텍스트뷰와 버튼의 기본적인 사용법에 대해 알아보려고 합니다. 개발환경 셋팅 후 처음으로 만들어보는 Hellow Kotlin 예제라고 생각하시면 됩니다.


참고로 앞으로 기본적인 설명은 왠만하면 주석으로 대체할 생각이며 안드로이드 코틀린 포스팅의 경우 자바를 어느정도 이해하시고 있다고 가정하고 진행합니다.


1. 레이아웃


<LinearLayout 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"
android:orientation="vertical"
tools:context="com.kotlin_test.Activity.HellowWorldActivity">

<TextView
android:id="@+id/txtHellow"
android:layout_width="match_parent"
android:layout_height="50dp"
android:textSize="20dp"
android:textStyle="bold"
android:gravity="center"/>

<Button
android:id="@+id/btn_clear"
android:text="Text Clear"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_print_01"
android:text="print_01"
android:layout_width="match_parent"
android:layout_height="50dp" />
<Button
android:id="@+id/btn_print_02"
android:text="print_02"
android:layout_width="match_parent"
android:layout_height="50dp" />

<Button
android:id="@+id/btn_print_03"
android:text="print_03"
android:layout_width="match_parent"
android:layout_height="50dp" />
</LinearLayout>







2. 소스


import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.kotlin_test.R
import kotlinx.android.synthetic.main.activity_hellow_world.*

class HellowWorldActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_hellow_world)

btn_clear.setOnClickListener {
txtHellow.setText("")
}

btn_print_01.setOnClickListener {
txtHellow.setText("Hellow Kotlin_01")
}

// val 변수 사용
btn_print_02.setOnClickListener {
// 변경 불가능한 변수 - val
// 자바로 말하면 final
val nameStr : String = "Kotlin_02"
txtHellow.setText("Hellow $nameStr")
}

// var 변수 사용
btn_print_03.setOnClickListener {
// 변경 가능한 변수 - var
var nameStr : String = "Test"
nameStr = "Kotlin_03"
txtHellow.setText("Hellow $nameStr")
}

}
}


위 소스를 보시면 자바와는 다른점이 확연히 느껴지실 겁니다. 달라진 점에 대해서는 차근차근 차후 포스팅에서 설명하겠지만 현재 눈에 보이는 가장 큰 차이는 코틀린은 데이터바인딩을 지원해서 레이아웃에 있는 뷰를  findViewById 할 필요가 없이 바로 id로 호출하여 사용이 가능하다는 점입니다.




3. 실행 결과






포스팅 OS : Mac

검색어 : 자바(Java), 배열(Array), 마름모(Diamond)




오늘은 자바 기초 공부를 위해 배열을 사용해 입력받은 정수에 따라 점점 커지는 마름모 그리는 방법에 대해 포스팅합니다.


이 마름모 그리기는 자바를 처음 공부하기 시작했을 때 많이들 접하는 문제인데 사실 정답은 없는 문제입니다. 여기서 정답이 없다는 것이 무슨 뜻이냐면 어떤 소스가 되었던 마름모만 그려지면 된다는 것을 의미합니다. 제가 작성한 소스가 정답은 아니라는 거죠. 누군가는 저 소스보다 더 간단하고 쉽게 마름모를 그릴 수도 있습니다. 


잠깐 잡담을 하고 가자면 개발은 본업으로 삼고 몇년째 이일을 하고 있지만 잘짜여진 소스가 일하는데 있어서 크게 중요한 것은 아닙니다. 물론 머리 좋은 사람이 보기 쉽고 짧게 작성해 놓은 소스라면 더 좋겠지만 프로젝트를 진행해나감에 있어서 일단 목표했던 기능이 제대로 구현되고 있는지가 먼저라고 생각합니다. 당연히 이것은 제 개인적인 생각입니다. 제 스타일은 그렇거든요. 일단 기능 구현 후 차차 소스를 정리해나가는 타입입니다. 처음부터 정리된 소스를 추구하는 분들도 있고 저같은 사람도 있습니다. 스타일은 중요하지 않습니다. 이 마름모 소스와 마찬가지로 뭐로 가든 일단 마름모만 그려지면 됩니다.


왜 이 긴 잡담을 했냐면 이 글을 보시는 여러분이 본인 스스로 만든 마름모 소스와 제 소스의 방법이 다르다 해서 저게 맞고 이게 틀리다 혹은 이게 맞고 저게 틀리다가 아니라는 것을 말하고 싶었습니다. 더 좋은 방법을 쓴 좋은 소스가 있다면 그것을 자신의 것으로 흡수하여 자유자재로 사용할 수 있게 제대로 소화하기만 하면 됩니다. 


잡담은 여기까지 하고 마름모 그리기 소스를 보시겠습니다. 소스에 대한 설명은 주석으로 간략하게 달아 놓았습니다. 설명을 주저리주저리 길게 써봤자 본인들 실력엔 도움이 되지 않습니다. 주석을 보고 이해가 안되는 점은 소스를 차근차근 분석해서 생각해보세요. 그 과정이 본인의 실력을 늘리는 피와 살이 됩니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Scanner;
 
public class Diamond {
 
    public static void main(String[] args) {
        /* 마름모 그리기 */    
    
        System.out.println("숫자를 입력해주세요.");
        Scanner input = new Scanner(System.in);
        
        int answer;                    // 입력받은 정수
        int center;                    // 가운데 행
        
        // 스캐너로 정수 입력 받기
        answer = input.nextInt();   
        
        // 입력받은 정수를 가공하여 마름모가 그려질 가로, 세로 길이 구하기
        answer = answer * 2 + 1;
        
        // 가운데 행 위치 지정
        center = answer/2;
        
        // 가공한 정수를 배열 생성에 사용
        char[][] dia = new char[answer][answer]; 
        
        int start = center;    // 점을 찍을 시작 지점
        int end = center;      // 점을 찍을 종료 지점
        
        // 마름모 생성
        for(int a=0 ; a < answer ; a++){
            for(int b=0 ; b < answer ; b++){
                if(start <= b && b <= end) {
                    dia[a][b] = '*';
                }else {
                    dia[a][b] = ' ';
                }
            }
            
            // 중간에서 점 찍는 위치 반전
            if(a < center) {
                start--;
                end++;
            }else {
                start++;
                end--;
            }
        }
        
        // 마름모 배열 출력
        for(int a=0 ; a < answer ; a++){
            for(int b=0 ; b < answer ; b++){
                System.out.print(dia[a][b]);
            }
            System.out.println();
        }
    }
}
cs



위 소스를 실행하면 아래와 같이 마름모가 그려집니다.

(왼쪽 상단에 숫자는 입력한 정수 입니다.)






다음 포스팅은 점점 커지는 별 그리기 포스팅을 하도록 하겠습니다.


포스팅 OS : Mac
검색어 : 디버그(Debug), 릴리즈(Release), 빌드(Buiild), 벨류(Value)
 
안드로이드 스튜디오로 앱을 소스를 관리할 때 디버그 빌드와 릴리즈 빌드의 벨류값을 따로 관리 하고 싶을 때 사용한다.
 
예를 들어 하나의 텍스트 뷰에 디버그 일때와 릴리즈 일때 각각 다른 텍스트를 보여주고 싶을 때 사용 가능하다. 
Ex)
- 디버그 빌드 일때는 텍스트로 '디버그 모드'를 노출
- 릴리즈 빌드 일때는 텍스트로 '릴리즈 모드'를 노출 
 
사용법은 아래와 같다.
 
1. build.gradle(Module:app)에서 아래와 같이 벨류를 생성 할 수 있다.
android {
    ...

    buildTypes {
        debug {
            // 레이아웃 벨류 사용법
            resValue("string", "testvalue", "디버그 모드")

            // 자바 벨류 사용법
            buildConfigField "String",  "TestValue01", "\"디버그 모드\""
            buildConfigField "int",     "TestValue02", "1234567890"
            buildConfigField "boolean", "TestValue03", "true"

        }
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

            // 레이아웃 벨류 사용법
            resValue("string", "testvalue", "릴리즈 모드")

            // 자바 벨류 사용법
            buildConfigField "String", "TestValue01", "\"릴리즈 모드\""
            buildConfigField "int",     "TestValue02", "0987654321"
            buildConfigField "boolean", "TestValue03", "false"
        }
    }
}
- 위와 같이 같은 벨류 명으로 debug와 release에 값을 다르게 생성하면 각 모드에서 해당 값으로 사용 가능하다.
 
1) resValue
- XML에서 사용할 수 있는 벨류
- 생성한 벨류는 모두 generated.xml에 자동으로 생성된다. 
- generated.xml : 아래와 같이 resValue로 생성한 변수가 생성되어 있는 것이 확인 가능하다.
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <!-- Automatically generated file. DO NOT MODIFY -->

    <!-- Values from build type: release -->
    <string name="testvalue" translatable="false">릴리즈 모드</string>

</resources>
2) buildConfigField
- 자바 소스에서 사용 가능한 벨류.
- 생성한 벨류는 모두 BuildConfig.java에 자동으로 생성된다.
- Buildconfig.java : 아래와 같이 buildConfigFeild로 생성한 변수가 생성되어 있는 것이 확인 가능하다.

public final class BuildConfig {
public static final boolean DEBUG = Boolean.parseBoolean("true");
public static final String APPLICATION_ID = "com.linecorp.advertise.buildmodetest";
public static final String BUILD_TYPE = "debug";
public static final String FLAVOR = "";
public static final int VERSION_CODE = 1;
public static final String VERSION_NAME = "1.0";
// Fields from build type: debug
public static final String TestValue01 = "디버그 모드";
public static final int TestValue02 = 1234567890;
public static final boolean TestValue03 = true;
}

2. 위에서 생성한 벨류를 사용해보자
1) resValue 사용법
- 아래와 같이 화면 레이아웃 xml에 벨류값을 불러서 사용한다.
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/testvalue" />
2) buildConfigField 사용법
- 아래와 같이 자바 소스로 벨류값을 불러서 사용한다.
TextView testValue01 = findViewById(R.id.txt_testValue01);
testValue01.setText(BuildConfig.TestValue01);
 
 
 
 
 
 

 

+ Recent posts