<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">
<TextView
android:id="@+id/tv1"
android:text="textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/TextAppearance.AppCompat.Large"/>
<ListView
android:id="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
class MainActivity : AppCompatActivity() {
// 문자열이 담긴 배열을 만들고 ListView에 뿌린다.
var data = arrayOf("List1", "List2", "List3", "List4", "List5", "List6", "List7", "List8", "List9", "List10")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 1) 컨텍스트 : 어떠한 작업을 하기위해서 필요한 정보가 담겨져 있는 객체
// 2) 레이아웃
// 3) 뿌릴 값
var adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, data)
lv1.adapter = adapter
// 1. 이너 클래스 리스너 형태로 등록
var listener = ListListener()
lv1.setOnItemClickListener(listener)
// 2. 람다식으로 등록, adapterView는 넘어오는 data이고, i가 인덱스이다.
lv1.setOnItemClickListener { adapterView, view, i, l ->
tv1.text = data[i]
}
}
// 1. 이너 클래스 리스너 형태로 등록
inner class ListListener : AdapterView.OnItemClickListener{
override fun onItemClick(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
// p2 는 사용자가 입력한 인덱스 번호가 된다.
tv1.text = data[p2]
}
}
}
가장 기본적인 ListView이다. 동적으로 데이터를 나열하고 조작하고 싶을 때 이용한다. 가장 단순한 형태로 조작이 가능하지만 지금은 리사이클러뷰를 쓰는게 맞다. 하지만 리사이클러뷰를 쓰기 위해서는 아는게 좋다.
기본적으로 자바때 했던 형태랑 거의 같다. 레이아웃을 안드로이드에서 제공하는 가장 기본적인 레이아웃을 이용했고, 배열을 이용한 가장 기본적인 형태이다. 오버라이딩 메서드가 한 가지라 람다식으로 가능하다.
이외에 사용자가 직접 레이아웃을 만들어서 사용하는 방법도 있다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:text="TextView"
style="@style/TextAppearance.AppCompat.Large"/>
</LinearLayout>
class MainActivity : AppCompatActivity() {
// 문자열이 담긴 배열을 만들고 ListView에 뿌린다.
var data = arrayOf(
"List1",
"List2",
"List3",
"List4",
"List5",
"List6",
"List7",
"List8",
"List9",
"List10"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 3번째 인자에 문자열을 지정할 TextView id를 넣어줘야한다.
var adapter = ArrayAdapter(this, R.layout.row1, R.id.textview, data)
lv1.adapter = adapter
lv1.setOnItemClickListener { adapterView, view, i, l ->
tv1.text = data[i]
}
}
}
맨 위의 기본 adapter와 다른 점은 직접 리소스 레이아웃을 만들어서 사용했다는 점이다. 3번째 인자에 문자열을 지정할 TextView id를 넣어줘야한다. 여기서 TextView의 id라고 하면 직접 만든 레이아웃의 TextView에 기입한 id가 되겠다. 자바 때와 아주 동일하다..
레이아웃에 항목이 3개 이상일 때..
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview1"
android:text="a"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextAppearance.AppCompat.Large"/>
<TextView
android:id="@+id/textview2"
android:text="b"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="@style/TextAppearance.AppCompat.Large"/>
</LinearLayout>
</LinearLayout>
class MainActivity : AppCompatActivity() {
// 이미지는 미리 넣어두셔야 합니다.
var imgRes = intArrayOf(
R.drawable.imgflag, R.drawable.imgflag2, R.drawable.imgflag3,
R.drawable.imgflag4, R.drawable.imgflag5, R.drawable.imgflag6,
R.drawable.imgflag7, R.drawable.imgflag8
)
var data1 = arrayOf(
"1", "2", "3", "4", "5", "6", "7", "8"
)
var data2 = arrayOf(
"11", "22", "33", "44", "55", "66", "77", "88"
)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 두 번째 Any는 리소스도 들어가고 문자열도 들어가고 구분이 없다는 뜻으로 사용한다.
var list = ArrayList<HashMap<String, Any>>()
var idx = 0;
// 각각의 리소스 들을 map에 넣고 list에 add 한다.
while (idx < data1.size) {
var map = HashMap<String, Any>()
map.put("flag", imgRes[idx])
map.put("data1", data1[idx])
map.put("data2", data2[idx])
list.add(map)
idx++
}
// 키 값과 아이디 값을 병렬로 ..
var keys = arrayOf("flag", "data1", "data2")
var ids = intArrayOf(R.id.imageView, R.id.textview1, R.id.textview2)
// SimpleAdapter을 통해서 리스트와 각각의 항목을 구성할 레이아웃, 쌍으로된 키와 아이디를 리스트를 넣는다.
var adapter = SimpleAdapter(this, list, R.layout.row, keys, ids)
lv1.adapter = adapter
// 이후 리스너는 전과 마찬가지이다.
}
}
문자열을 두개 넣고 싶은 경우
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
<ListView
android:id="@+id/lv1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
class MainActivity : AppCompatActivity() {
var data1 = arrayOf("문자열1", "문자열2", "문자열3", "문자열4", "문자열5", "문자열6")
var data2 = arrayOf("String1", "String2", "String3", "String4", "String5", "Strin6")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var list = ArrayList<HashMap<String, String>>();
var idx = 0
while (idx < data1.size) {
var map = HashMap<String, String>();
map.put("str1", data1[idx])
map.put("str2", data2[idx])
list.add(map)
idx++
}
var key = arrayOf("str1", "str2")
var ids = intArrayOf(android.R.id.text1, android.R.id.text2)
var adapter =
SimpleAdapter(this, list, android.R.layout.simple_expandable_list_item_2, key, ids)
lv1.adapter = adapter
lv1.setOnItemClickListener { adapterView, view, i, l ->
tv1.text = data1[i]
}
}
}
이 방식도 크게 다르지 않다. 다만 SimpleAdapter를 쓰고 있고 키값과 아이디를 쌍으로 맞춰서 넣어줘야한다는 점이다. ListView는 간단히 하고 이후에 RecyclerView를 다뤄본다.
궁금한 점은 덧글로 남겨주세요.
'안드로이드' 카테고리의 다른 글
[Android Kotlin] 안드로이드 코틀린 Spinner (0) | 2020.03.24 |
---|---|
[Android Kotlin] 안드로이드 코틀린 Custom Adapter (0) | 2020.03.24 |
[Android Kotlin] 안드로이드 코틀린 ImageView (0) | 2020.03.21 |
[Android Kotlin] 안드로이드 코틀린 EditText (0) | 2020.03.21 |
[Android Kotlin] 안드로이드 코틀린 Seek Bar (0) | 2020.03.21 |