반응형

ListFragment

설명

  • ListView를 보다 쉽게 사용하기 위해 제공되는 Fragment
  • ListView의 id를 "@android:id/list"로 지정해야 한다.

코드

res/layout/fragment_test_list.xml
<?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="match_parent"
    android:orientation="vertical">

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
TestListFragment
class TestListFragment : ListFragment() {
    private val list = arrayOf("항목1", "항목2", "항목3")

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_test_list, container, false)
        val adapter = ArrayAdapter<String>(activity!!, android.R.layout.simple_list_item_1, list)

        listAdapter = adapter

        return view
    }

    override fun onListItemClick(l: ListView, v: View, position: Int, id: Long) {
        Toast.makeText(context, list[position], Toast.LENGTH_SHORT).show()
    }
}
res/layout/activity_main.xml
<?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="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/frameLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>
MainActivity
class MainActivity : AppCompatActivity() {
    private val testListFragment = TestListFragment()

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

        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.frameLayout, testListFragment)
        transaction.commit()
    }
}

참고

반응형

'Development > Android' 카테고리의 다른 글

[Android] Thread & Handler  (0) 2021.02.09
[Android] DialogFragment  (0) 2021.02.09
[Android] Fragment  (0) 2021.02.09
[Android] DatePicker  (0) 2021.02.09
[Android] ListDialog  (0) 2021.02.09

+ Recent posts