[Android/Kotlin] Anko 확장 활용-2

SoyoungLee·2021년 6월 14일
0

안드로이드/코틀린

목록 보기
4/68
post-thumbnail

💌 DSL을 이용한 레이아웃 만들기

  • xml 작업 뷰 -> 코드 재활용 불편, 불필요한 파싱으로 성능 저하
  • 소스 코드상에서 직접 뷰의 코드 작성 해 xml 변환에 따른 오버헤드 제거

📌 Anko Layouts 활용하기

💜 DSL 이용한 레이아웃 작성

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main)    // 주석처리

        verticalLayout{ // vertical 속성을 가지는 LinearLayout
            val name = editText() { hint = "Name" } // editText 객체
            button("Say Hello"){    // Button 뷰
                onClick { toast("Hello, ${name.text}") }    // 클릭 이벤트 처리
            }
        }
    }
}

💜 분리된 클래스에서 레이아웃 작성

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        MainUI().setContentView(this)
    }
}

// 분리된 레이아웃을 위한 클래스
class MainUI :AnkoComponent<MainActivity>{
    override fun createView(ui: AnkoContext<MainActivity>): View = with(ui) {
        verticalLayout{ 
            val name = editText() { hint = "Name" } 
            button("Say Hello"){  
                onClick { toast("Hello, ${name.text}") }  
            }
        }
    }
}

💜 LayoutParams 이용하기

verticalLayout{
	val name = editText() { hint = "Name" }
	button("Say Hello"){
		onClick { 
        		toast("Hello, ${name.text}") 
        		}
	}.lparams(width = wrapContent){ // width와 height에 wrapContent, matchParent 설정 가능
		horizontalMargin = dip(20)   // 왼쪽 오른쪽 마진설정 <-> verticalMargin
		topMargin = dip(10) // 4개 모든 마진 설정
            }
	}

💜 이벤트 리스너 처리

// 텍스트 뷰와 탐색 바 추가
val percent = textView() { text = "Seek!"}
            seekBar {
                onSeekBarChangeListener {
                    onProgressChanged { seekBar, progress, fromUser ->
                        percent.text = progress.toString()
                    }
                }
            }

💜 레이아웃 안에 레이아웃

verticalLayout{
            linearLayout{
                var button = button("Some text")
            }

💜 다양한 뷰의 속성

textView {
            text = "this is a text"
            textSize = 24f
            textColor = Color.GREEN
            textAlignment = View.TEXT_ALIGNMENT_CENTER
          }

var view_list = listView {
            }.lparams(width = matchParent, height = matchParent){ }

editText{
             hint = "placeholder of text"
             textSize = 24f
         }

imageView {
                setImageResource(R.drawable.ic_baseline_auto_awesome_24)
            }.lparams(width= matchParent, height = 100)
profile
Android Developer..+ iOS 슬쩍 🌱 ✏️끄적끄적,,개인 기록용 👩🏻‍💻

0개의 댓글