반응형

 

아래와 같이 클래스를 만들었을 경우

1.  Override, 다형성

open class Country ( var fullName: String, var capital: String, var language: String)  {

    fun printFullName () {
        println("fullName: $fullName")
    }
    fun printCapital () {
        println("capital: $capital")
    }
    fun printLanguage () {
        println("language: $language")
    }
    open fun singNationalAnthem () {
        println("singNationalAnthem")
    }
}

class Korea (fullName: String, capital: String, language: String) : Country( fullName, capital, language) {
    override fun singNationalAnthem () {
        super.singNationalAnthem()
        println("sing Korea")
    }
}


class USA ( fullName: String, capital: String, language: String) : Country( fullName, capital, language) {
    override fun singNationalAnthem () {
        super.singNationalAnthem()
        println("sing USA")
    }
}

 

  1. Country 라는 클래스를 Korea, USA 라는 클래스에서 상속.
  2. 자식 클래스에서는 super.METHOD 를 통해 부모 클래스의 메서드를 호출 할 수 있다.
  3. +커스터마이징이 가능하다 (== 다형성)

 

fun main (args: Array<String>) {
    val korea = Korea("대한민국", "서울", "한국어")
    korea.singNationalAnthem()
    val usa = USA("미국", "워싱턴", "영어")
    usa.singNationalAnthem()
}

/** output
singNationalAnthem
sing Korea
singNationalAnthem
sing USA
*/

이렇게 출력이 된다.

Java의 문법과는 또 달라서 [ Java(public) / Kotlin(open) ] 신기하다.
뭔가 public 공공의 라는 뜻보다는 open 이 더 직관적이기도 하고

 


 

2. Abstract. 추상매서드

다음으로 추상메서드에 대해 메모한다.

//추상클래스
abstract class Game {
    //일반메서드
    fun startGame () {
        println("Game Start")
    }

    //추상메서드
    abstract fun printGameName ()
}

class OverWatch: Game() {
    //추상메서드는 하위 클래스에서 반드시 구현해야함
    override fun printGameName() {
        println("This game is OverWatch.")
    }
}

Game이라는 클래스를 만들었다.
Game > 메서드로 printGameName 이라는 메서드를 만들어놓았다.
: 추상메서드는 반드시!!! 오버라이딩 한 메서드에서 만들어야한다.

fun main (args: Array<String>) {
    val overwatch = OverWatch() //새로운 인스턴스 생성

    overwatch.startGame()
    overwatch.printGameName()
}

새로운 인스턴스 overWatch 를 생성.
해당 클래스에 선언된 메서드를 실행하였다.
printGameName 메서드는 추상메서드로 선언(abstract)

예전에는 이게 무슨소린지 전혀 이해를 못했었는데, 다시 보니 또 바로 이해되는게 신기하다.

반응형

코틀린을 사용하는데에 차이점이 존재했다.

1. Array

//Java
String[] javaArray = {"1", "2", "3"};

//Kotlin  : Array<String> 부분은 생략이 가능하다.
val kotlinArray: Array<String> = arrayOf("1", "2", "3");
val kotlinArray arrayOf("1", "2", "3");

문법이 너무 신기하다.


2. 배열의 사용법

//Until 끝 값을 포함하지 않는 범위를 생성 (시작값 ≤ i < 끝값).
for (i in 1 until 10) {
    println(i) // Prints numbers from 1 to 9 (10 is excluded)
}

//DownTo 값을 감소시키며 반복.
for (i in 10 downTo 1) {
    println(i) // Prints numbers from 10 to 1
}

//Step 반복 간격을 설정 (기본값은 1).
for (i in 1..10 step 2) {
    println(i) // Prints 1, 3, 5, 7, 9
}

꽤나 많은 것들이 확장 되는 것 같다.


3. print

여러 가지가 있지만, 그 중에 JavaScript template literal 처럼 사용하는게 너무 신기했다.

//JavaScript
const literalWord = 'value of Literal'
console.log(`literalWord : ${literalWord}`)

//Kotlin
val literalWord: String = "value of Literal"
println("literalWord : $literalWord");

어떤가? 너무 유사해보이지 않은가??


4. when

fun getGrade (examScore: Int): Char {
    return when {
        examScore >= 90 -> 'A'
        examScore >= 80 -> 'B'
        examScore >= 70 -> 'C'
        examScore >= 60 -> 'D'
        else -> 'F'
    }
}
val grade = getGrade(80)
println("grade: $grade") //B

JavaScript 에서 switch case 와 동일해보인다.
문법자체는 더 간결하고 깔끔하며 break; 를 걸어줄 필요가 없어서 편의성이 더 높다.


5. set

//1. mutable set : 가변
val mutableAnimalSet = mutableSetOf("Lion", "Elephant", "Dog", "1", "2", "1")
println("mutableAnimalSet: $mutableAnimalSet")

//2. immutable set : 불변
val animalSet = setOf("Lion", "Elephant", "Dog", "1", "2", "1")
println("animalSet: $animalSet")

신기했던 건 setOf, mutableSetOf 함수를 사용하면, 중복된 내용은 삭제가 된다는 것이었다.

//output
mutableMap: {key1=Lion, key2=Elephant, key3=Dog}




React.js, Next.js 등을 공부하던 와중
회사에서 인턴 직원분이 백엔드 코드를 짜고 제출하는 모습을 봤다
내용도 꽤나 괜찮았다
이에 자극받아 백엔드 쪽 공부의 필요성을 느끼게 되어 Kotlin 코틀린 공부를 시작하게 되었다.

 

반응형

안녕하세요 상훈입니다.

Kotlin 에서 button 클릭 시, 혹은 image button 클릭 시,
Toast 메시지를 출력하는 방법에 대해 포스팅 하겠습니다.

 

var contentToast = Toast.makeText(this, "Content button clicked", Toast.LENGTH_SHORT)
contentToast.show()

toast메시지 생성 방법은 위와 같습니다.
변수에 toast 메시지 내용할당하고, show() 함수를 통해 해당 내용을 체이닝하여 출력하는 방식.

 

반응형

 

 

예제1)

버튼 클릭 시, toast 메시지 출력

private lateinit var binding: ActivityMainBinding

onCreate(){

  binding.contentBtn.setOnClickListener {
      var contentToast = Toast.makeText(this, "Content button clicked", Toast.LENGTH_SHORT)
      contentToast.show()
  }
       
}

contentBtn이라는 id 를 가진 Image Button에 대한 클릭 이벤트 안에 Toast 메시지를 출력하도록 작성하였습니다.

 

 

예제2) : 좋아요 버튼

이미지 버튼 2개 준비합니다. [ 클릭 전, 클릭 후 ] 의 각각의 이미지를 나타냅니다.

binding.heartBtn.setOnClickListener {
    if (!liked) {
        binding.heartBtn.setBackgroundResource(R.drawable.checkedheart);
        var likeToast = Toast.makeText(this, "Liked!!", Toast.LENGTH_SHORT)
        likeToast.show()
    } else {
        binding.heartBtn.setBackgroundResource(R.drawable.heart);
        var likeToast = Toast.makeText(this, "UnLiked!!", Toast.LENGTH_SHORT)
        likeToast.show()
    }
    liked = !liked; // reverse
}

 

before  &  after

 

클릭 시 toast 메시지 출력과 빈 하트가 빨간 하트로 변경되게 설정하였습니다.

vue로 따지자면 v-if( ! liked ) / else 가 되겠네요.

반응형

 

values / style.xml

style.xml 파일을 하나 만들어주세요.

<?xml version="1.0" encoding="utf-8"?>
<resources>

<!-- Base application theme. -->
    <style name="ThemeActionBar"
        parent="Widget.AppCompat.Light.ActionBar.Solid">
        <item name="android:background">@null</item>
        <!-- Support library compatibility -->
        <item name="background">@null</item>
    </style>
</resources>

해당 내용을 작성합니다. 

@null 로 처리하여 없애버립니다(투명하게)

 

2. themes / themes.xml 

이곳으로 이동해주세요
이 아래에 작성해주세요.

 

<!-- Customize your theme here --> 아래에 작성해주세요

 

<!-- actionbar -->
        <item name="android:actionBarStyle">@style/ThemeActionBar</item>
        <item name="android:windowActionBarOverlay">true</item>
        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/ThemeActionBar</item>
        <item name="windowActionBarOverlay">true</item>

 

Avd 재구동! ( 에뮬레이터 )

 

반응형

 

 

원래는 있던 ActionBar가 사라진 것을 알 수 있습니다.

 

 

이전 모습 비교:

 

[ Kotlin, Java ] 안드로이드 스튜디오 - 비디오 배경화면 설정하기

mainActivity.kt val videoUri = Uri.parse("android.resource://" + packageName + "/" + R.raw.first ); binding.videoView.setVideoURI(videoUri); binding.videoView.start(); binding.videoView.setOnComplet..

code-hoon.tistory.com

감사합니다.

 

 

참고

 

Material Design Transparent ActionBar

I'd like to know if anyone knows how to make an activity with transparent action bar, like the one you have in the new Google Play Store when you go to an app's page. I don't care about the scroll...

stackoverflow.com

 

 

How to change the color of Action Bar in an Android App? - GeeksforGeeks

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

www.geeksforgeeks.org

 

반응형

mainActivity.kt

val videoUri = Uri.parse("android.resource://" + packageName + "/" + R.raw.first );
        binding.videoView.setVideoURI(videoUri);
        binding.videoView.start();
        binding.videoView.setOnCompletionListener {
            binding.videoView.start();
        }

 

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">
    
    <VideoView
        android:id="@+id/videoView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentTop="true"
        android:layout_alignParentBottom="true"

        />
</RelativeLayout>

 

 

ConstraintLayout -> RelativeLayout으로 변경.

VideoView를 삽입하고, 해당 내용을 작성한다.

 

반응형

 

=> VideoView Layout 아래부터 코드를 작성하면 동영상 레이아웃이 가장 하단에 쌓여,

z-index가 가장 낮은 순위가 된다.

 

포토샵으로 보자면, 동영상 레이아웃을 가장 아래에 놓고 위에 다른 레이아웃들을 쌓는 형태이다.

 

 

 

 

How to create a video background for my app in Kotlin? setVideoURI and setVideoPath are not working - Stack Overflow

 

webcache.googleusercontent.com

 

반응형

 

java.lang.NullPointerException: Attempt to invoke virtual method 
'android.view.WindowInsetsController com.android.internal.policy.DecorView
.getWindowInsetsController()'on a null object reference

 

전체화면 적용 중에 

해당되는 에러가 발생하였다.

 

이 이유는 onCreate() 안에서 setContentView가 선언되기 전에 전체화면 적용하는 코드를 작성하였기 때문이다.

이와 같이 setContentView(binding.root)끝난 후에 해당 내용을 작성해주는 것으로 이동시키면 해결.

 

반응형

 

 

 

stackoverflow에서 발췌

 

How to set fullscreen in Android R?

I need to put a screen in fullscreen in my app. For this I am using this code: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(W...

stackoverflow.com

 

 

 

반응형

 

 

// 상태바 및 액션바 제거
        @Suppress("DEPRECATION")
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){
            window.insetsController?.hide(WindowInsets.Type.statusBars())
        }else{
            window.setFlags(
                WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN
            )
        }

해당 내용을 onCreate() 안에 작성해줍니다.

 

fullscreen이 적용된 모습

 

반응형

 

 

 

 

How to set fullscreen in Android R?

I need to put a screen in fullscreen in my app. For this I am using this code: override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) requestWindowFeature(W...

stackoverflow.com

 

 

[Android Studio] 액션바(ActionBar)/타이틀바, 상태바(StatusBar) 숨기기

안녕하세요 안드로이드 스튜디오를 처음 개발하는 분들이라면 앱 상단의 액션바/타이틀바와 상태바를 숨겨서 큰 화면으로 내가 개발한 앱을 띄우고 싶은 경우가 있습니다 이번 포스팅에서는

crazykim2.tistory.com

 

+ Recent posts