xml에 있는 view를 컨트롤하기 위해서는 id값이 필요하다
class에서는 id값을 찾아와서(findViewById)
컨트롤한다~!
단, findViewById는 setContentView아래에 있어야 한다.
*** 버튼 이벤트 달기 ***
1. 메서드를 속성에 달아주기( OnClick속성)
2. innerClass로 OnClick Override: SAM(람다식에서 생략할 수 있는 경우)
3. interface를 상속받게 만들어 준다
01. intent의 개념
안드로이드 4대 컴포넌트
- Activity: Activity(액티비티)는 반드시 하나 이상은 존재해야 한다.
[사용자에게 UI가 있는 화면을 제공하기 위한, 화면 단위를 구성하는 컴포넌트]
- Service: 어플리케이션이 백그라운드에서 동작하는 작업을 수행
- BroadCastReceiver: 시스템이나 어플리케이션으로부터 다양한 이벤트나 정보받아 알맞은 작업을 수행
- Content Provider: 다른 어플리케이션에 데이터를 제공 및 관리 예시로, 특정 앱에서 연락처 정보에 대한 내용이 필요하면 연락처 앱을 통해 연락처 정보를 가져올 수 있습니다.
이4개의 중간에서 데이터를 전달해주는것이 intent 이다.
intent: 컴포넌트들은 각각 intent(인텐트)에 의해 활성화
인텐트: 메세지 객체, 어떤 행동을 수행할 지에 대한 명령/작업에 대한
02 묵시적 인텐트
묵시적(암묵적)intent: 약속된 액션(Action)을 정하여 안드로이드에서 제공하는 응용 프로그램을 실행하는 인텐트
다른 액티비티를 실행하거나 데이터를 전달할 수 있는 안드로이드 구성 요소
1. view id 값 찾아오기
2. Iv에 어떤 item을 클릭했는지 구분(판단)
3. 해당 색상코드를 버튼을 눌렀을 때 intent에 실어서 보내주자(SecondActivity로)
4. SecondActivity 에서 intent에 붙어있는 데이터를 때서 사용(setBackground에 사용)
5. btnPre를 누르면 이전페이지로 돌아간다.
[전화걸기]
[MainActivity.kt]
package com.example.ex20221128
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.core.app.ActivityCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnCall = findViewById<Button>(R.id.btnCall)
// 암묵적 intent
// : 안드로이드 내부에 있는 어플리케이션을 실행
// Chrome, Camera, Message, Call
//Intent의 사용용도
// 1. 액션, 데이터
// 2. Android 4대 구성요소간의 데이터 주고받을 때
btnCall.setOnClickListener {
//btnCall을 누르면 전화가 가게 만들어보자
// 데이터 : 전화번호
// URi : key, value
// "tel: 010-1234-5678"
var uri = Uri.parse("tel: 010-1234-5678")
var intent = Intent(Intent.ACTION_CALL, uri)
// permission:권한
// 사용자한태 권한을 줄껀지 물어봐 줘야함!
// ActivityCompat
// checkSelfPermission(): 지금 현재 권한이 부여되어 있는지
// (현재 페이지 정보, 어떤 권한 인지)
// 결과값으로 승인이 되어있는지? 안되었는지? 받아온다
if( ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
// 승인이 안되어있는 상태라면 알림창을 띄워서 승인할 수 있도록
//ActivityCompat는 확인하는 기능 요청하는 기능이 둘다 들어가 있음
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.CALL_PHONE),0
)
// requestCode: 내가 뭘 요청한건지 구분하기위한 숫자
return@setOnClickListener
}
// Intent 실행시키기
startActivity(intent)
}
}
}
[AndroidMainfest.xml]
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Ex20221128"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.lib_name"
android:value="" />
</activity>
</application>
</manifest>
[MainActivity]
package com.example.ex20221128
import android.app.SearchManager
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.MediaStore
import android.widget.Button
import androidx.core.app.ActivityCompat
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnCall = findViewById<Button>(R.id.btnCall)
val btnWeb = findViewById<Button>(R.id.btnWeb)
val btnGoogle = findViewById<Button>(R.id.btnGoogle)
val btnSearch = findViewById<Button>(R.id.btnSearch)
val btnSms= findViewById<Button>(R.id.btnSms)
val btnPhoto = findViewById<Button>(R.id.btnPhoto)
// 암묵적 intent
// : 안드로이드 내부에 있는 어플리케이션을 실행
// Chrome, Camera, Message, Call
//Intent의 사용용도
// 1-1. 액션, 데이터
// 1-2 액션 -> Camera
// 2. Android 4대 구성요소간의 데이터 주고받을 때
btnCall.setOnClickListener {
//btnCall을 누르면 전화가 가게 만들어보자
// 데이터 : 전화번호
// URi : key, value
// "tel: 010-1234-5678"
var uri = Uri.parse("tel: 010-1234-5678")
var intent = Intent(Intent.ACTION_CALL, uri)
// permission:권한
// 사용자한태 권한을 줄껀지 물어봐 줘야함!
// ActivityCompat
// checkSelfPermission(): 지금 현재 권한이 부여되어 있는지
// (현재 페이지 정보, 어떤 권한 인지)
// 결과값으로 승인이 되어있는지? 안되었는지? 받아온다
if( ActivityCompat.checkSelfPermission(this,
android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED){
// 승인이 안되어있는 상태라면 알림창을 띄워서 승인할 수 있도록
//ActivityCompat는 확인하는 기능 요청하는 기능이 둘다 들어가 있음
ActivityCompat.requestPermissions(this,
arrayOf(android.Manifest.permission.CALL_PHONE),0
)
// requestCode: 내가 뭘 요청한건지 구분하기위한 숫자
return@setOnClickListener
}
// Intent 실행시키기
startActivity(intent)
}
//btnWeb을 클릭하면 구글 홈페이지가 보이게 만들자
btnWeb.setOnClickListener {
//데이터: 구글 주소(http://www.google.co.kr)
var uri = Uri.parse("http://www.google.co.kr")
var intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
}
//btnGoogle을 클릭하면 구글 맵을 보이게 만들어주자
btnGoogle.setOnClickListener {
// 액션, 데이터
// 데이터: 구글 맵은 get 방식
// 구글 맵 주소/ 경도, 위도
var uri = Uri.parse("https://google.com/maps?q=35.14670147841655,126.92215633785938")
var intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
}
//클릭했을 때 해당 키워드로 구글 검색
btnSearch.setOnClickListener {
//1. 검색하는 intent를 하나 생성한다
var intent = Intent(Intent.ACTION_WEB_SEARCH)
//2. 검색하고 싶은 키워드를 인텐트에 넣어준다
intent.putExtra(SearchManager.QUERY, "안드로이드")
//3. intent 실행
startActivity(intent)
}
// 사진 찍기
//M MediaStore: Emulator에서 동작할 수 있는 카메라, 저장소
btnPhoto.setOnClickListener {
var intent= Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivity(intent)
}
//btnSms를 클릭하면 문자를 보내는 페이지로 이동한 다음
// 내용을 꺼내올 예정
btnSms.setOnClickListener {
var intent = Intent(Intent.ACTION_SENDTO)
//문자 내용
//"sms_body"라는 Key 값이 value가 문자내용임을 구분할 수 있다
intent.putExtra("sms_body", "안녕하세요 조자연입니다")
//누구한테 보낼껀지에 대한 데이터 tel: ---> Uri
intent.data=Uri.parse("smsto:"+Uri.encode("010-1234-5678"))
startActivity(intent)
}
}
}
[FirstActivity]
package com.example.ex20221128
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.Button
import android.widget.ListView
class FirstActivity : AppCompatActivity() {
var color:String = "white"
//배경 색상을 저장해 Second Activity로 보내자!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_first)
val btnNext = findViewById<Button>(R.id.btnNext)
val lv = findViewById<ListView>(R.id.lv)
lv.setOnItemClickListener(object : OnItemClickListener{
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
//p2: position
//너, p0가 null 이면 어떡할래?
if(p0 !=null){
color = p0!!.adapter.getItem(p2).toString()
}
Log.d("찍어보자",color)
}
})
//inner class
//익명 클래스 anonymous class
btnNext.setOnClickListener(object : View.OnClickListener{
override fun onClick(v: View?) {
}
})
btnNext.setOnClickListener { v ->
}
// 버튼 클릭을 감지하는 리스너를 장착
// setOnClickListener
//
//
// //btnNext를 클릭했을때, SecondActivity로 이동!
// btnNext.setOnClickListener {
// //Activity로 이동하는 Intent(명시적 인텐트)
// // (시작Activity로 이동하는 Intent(명시적 인텐트)
// // (this, java class)
// // Kclass로 만들어진 Activity를 java class로 바꿔줘야한다
// // 액티비티명:: class.java
// var intent = Intent(this,
// SecondActivity::class.java
// )
//
// //실행!!!!
// startActivity(intent)
//Android 4대 구성요소
//Activity 화면을 구성
//Service (Background에서 동작) Activity에서 화면만 뺀거
//BR(Broadcast Receiver)
//CP(Content Provider)
// 카카오톡에서 다른사람에게 연락처를 전송하고자 할때
// 연락처 어플리케이션에서 연락처 정보를
// 카톡으로 넘김
//4대 구성요소간 정보를 매개하는
//Intent
// 명시적, 묵시적
// explicit, implicit
// btnNext를 누르면 SecondActivity로 color코드를 가지고 넘어간다
btnNext.setOnClickListener {
var intent = Intent(this@FirstActivity,
SecondActivity:: class.java)
intent.putExtra("color", color)
// 단방향 호출
startActivity(intent)
}
}
// ctrl + o (overriding)
// 혹은 우클릭 -> generate -> override methods
override fun onStart() {
super.onStart()
Log.d("생명주기","onStart입니다")
}
override fun onStop() {
super.onStop()
Log.d("생명주기","onStop입니다")
}
override fun onResume() {
super.onResume()
Log.d("생명주기","onResume입니다")
}
override fun onPause() {
super.onPause()
Log.d("생명주기","onPause입니다")
}
override fun onRestart() {
super.onRestart()
Log.d("생명주기","onRestart입니다")
}
}
[LoginActivity]
package com.example.ex20221128
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
class LoginActivity : AppCompatActivity() {
var loginId : String? = null
var loginPw : String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login2)
// 1. 3개의 component 초기화!!
val etId = findViewById<EditText>(R.id.etId)
val etPw = findViewById<EditText>(R.id.etPw)
val btnLogin = findViewById<Button>(R.id.btnLogin)
// 2. btnLogin을 클릭했을 때, etId와 etPw에 담긴 문자열을
// 각각 loginId와 loginPw에 저장!
btnLogin.setOnClickListener {
loginId = etId.text.toString()
loginPw = etPw.text.toString()
// 3. DB Activity로 이동하기 위한
// intent를 만들자!!
val intent = Intent(this, DBActivity::class.java)
intent.putExtra("loginId", loginId)
intent.putExtra("loginPw", loginPw)
startActivity(intent)
}
}
}
[DBActivity]
package com.example.ex20221128
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
class DBActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_db)
val tvResult = findViewById<TextView>(R.id.tvResult)
val loginId:String = intent.getStringExtra("loginId")!!
val loginPw:String = intent.getStringExtra("loginPw")!!
Log.d("로그인로그인", loginId + " : "+loginPw)
//ID : kyi
//PW:1234
if (loginId=="kyj" && loginPw=="1234"){
tvResult.text="로그인성공"
}else{
tvResult.text="로그인 실패"
}
}
}
[activity_db.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=".DBActivity">
<TextView
android:id="@+id/tvResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="48sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
[activity_first]
<?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=".FirstActivity">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.5" />
<Button
android:id="@+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="다음 페이지"
app:layout_constraintEnd_toEndOf="@+id/textView"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="이곳은 첫번째 페이지 입니다."
android:textSize="32dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
android:id="@+id/lv"
android:layout_width="0dp"
android:layout_height="0dp"
android:entries="@array/coclors"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/guideline2" />
</androidx.constraintlayout.widget.ConstraintLayout>
[activity_login2.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=".LoginActivity">
<EditText
android:id="@+id/etId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="120dp"
android:ems="10"
android:hint="ID를 입력하세요"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/etPw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="PW를 입력하세요"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="@+id/etId"
app:layout_constraintStart_toStartOf="@+id/etId"
app:layout_constraintTop_toBottomOf="@+id/etId" />
<Button
android:id="@+id/btnLogin"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:text="로그인"
app:layout_constraintEnd_toEndOf="@+id/etPw"
app:layout_constraintStart_toStartOf="@+id/etPw"
app:layout_constraintTop_toBottomOf="@+id/etPw" />
</androidx.constraintlayout.widget.ConstraintLayout>
[activity_main]
<?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">
<Button
android:id="@+id/btnCall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="100dp"
android:layout_marginEnd="32dp"
android:backgroundTint="#E3A9A9"
android:text="전화걸기"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btnWeb"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:backgroundTint="#E3A9A9"
android:text="홈페이지열기"
app:layout_constraintEnd_toEndOf="@+id/btnCall"
app:layout_constraintStart_toStartOf="@+id/btnCall"
app:layout_constraintTop_toBottomOf="@+id/btnCall" />
<Button
android:id="@+id/btnGoogle"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:backgroundTint="#E3A9A9"
android:text="구글 맵 열기"
app:layout_constraintEnd_toEndOf="@+id/btnWeb"
app:layout_constraintStart_toStartOf="@+id/btnWeb"
app:layout_constraintTop_toBottomOf="@+id/btnWeb" />
<Button
android:id="@+id/btnSearch"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:backgroundTint="#E3A9A9"
android:text="구글 검색"
app:layout_constraintEnd_toEndOf="@+id/btnGoogle"
app:layout_constraintStart_toStartOf="@+id/btnGoogle"
app:layout_constraintTop_toBottomOf="@+id/btnGoogle" />
<Button
android:id="@+id/btnSms"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:backgroundTint="#E3A9A9"
android:text="문자 보내기"
app:layout_constraintEnd_toEndOf="@+id/btnSearch"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="@+id/btnSearch"
app:layout_constraintTop_toBottomOf="@+id/btnSearch" />
<Button
android:id="@+id/btnPhoto"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:backgroundTint="#E3A9A9"
android:text="사진찍기"
app:layout_constraintEnd_toEndOf="@+id/btnSms"
app:layout_constraintStart_toStartOf="@+id/btnSms"
app:layout_constraintTop_toBottomOf="@+id/btnSms" />
</androidx.constraintlayout.widget.ConstraintLayout>
[activity_second.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:id="@+id/cl"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<Button
android:id="@+id/btnPre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="이전 페이지로"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
'Full Stack 교육 회고록' 카테고리의 다른 글
2022.11.30 - 안드로이드 전화번호부, 포켓몬 도감 만들기 (0) | 2022.12.01 |
---|---|
2022.11.29 안드로이드스튜디오 (0) | 2022.11.29 |
11/25- 안드로이드스튜디오(계산기, 로그인) / Node.js(Sequelize) (0) | 2022.11.25 |
11/24 node.js / kotlin (1) | 2022.11.24 |
11/23 - kotlin, 안드로이드 스튜디오, node.js (0) | 2022.11.23 |