DEV Community

ownership903
ownership903

Posted on

[Android Studio|Kotlin] Containers, Create a list

1) spinner

[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        var data = listOf("-do choice", "1","2","3","4","5","6","7","8")
        var adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data)
        with(binding) {
            spinner.adapter = adapter
            spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
                override fun onNothingSelected(p0: AdapterView<*>?) {
                }
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    result.text = data.get(p2)
                }
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.xml]

<TextView android:id="@+id/result"
<Spinner android:id="@+id/spinner"
Enter fullscreen mode Exit fullscreen mode

2) RecyclerView
[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        val data = loadMemoList()
        var adapter = CustomAdapter(data)
        binding.recyclerView.adapter = adapter
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
    }


    fun loadMemoList(): MutableList<Memo> {
        val memoList = mutableListOf<Memo>()
        for (no in 0..100) {
            val title = "it is kotlin android ${no + 1}"
            val date = System.currentTimeMillis()
            var memo = Memo(no, title, date)
            memoList.add(memo)
        }
        return memoList;
    }
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recyclerView"
<androidx.constraintlayout.widget.ConstraintLayout
Enter fullscreen mode Exit fullscreen mode

[CustomAdapter.kt]

class CustomAdapter(var listData:MutableList<Memo>) : RecyclerView.Adapter<CustomAdapter.Holder>() {
    //var listData = mutableListOf<Memo>()
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder {
        val binding = ItemRecyclerBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return Holder(binding)
    }
    override fun getItemCount() = listData.size
    override fun onBindViewHolder(holder: Holder, position: Int) {
        val memo = listData.get(position)
        holder.setMemo(memo)
    }
    class Holder(val binding: ItemRecyclerBinding) : RecyclerView.ViewHolder(binding.root) {
        lateinit var currentMemo: Memo
        init {
            binding.root.setOnClickListener {
                Toast.makeText(binding.root.context, "clicked item : ${currentMemo.title}", Toast.LENGTH_SHORT).show()
            }
        }
        fun setMemo(memo: Memo) {
            currentMemo = memo
            with(binding) {
                textNo.text = "${memo.no}"
                textTitle.text = "memo.title"

                var sdf = SimpleDateFormat("yyyy/MM/dd")
                var formattedDate = sdf.format(memo.timestamp)
                textDate.text = formattedDate
            }
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

[item_recycler.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="50dp"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/textNo"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="01" />

    <TextView
        android:id="@+id/textTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="5"
        android:text="title" />

    <TextView
        android:id="@+id/textDate"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:text="2020-01-01" />
</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

[Memo.kt]

data class Memo(
    var no: Int,
    var title: String,
    var timestamp:Long
    )
Enter fullscreen mode Exit fullscreen mode

3) add Fragment to Activity
[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        setFragment()
    }
    fun setFragment() {
        val listFragment: ListFragment = ListFragment()
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, listFragment)
        transaction.commit()
    }
}

Enter fullscreen mode Exit fullscreen mode

[ListFragment.kt]

class ListFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? { 
        return inflater.inflate(R.layout.fragment_list, container, false)
    }
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.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"
    android:visibility="visible"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Activity"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/frameLayout"
        android:name="com.example.myapplication.ListFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:layout="@layout/fragment_list" />

</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

[fragment_list.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=".ListFragment">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/title_list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="NEXT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

4) Fragment screen transition
[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    val listFragment by lazy { ListFragment() }
    val detailFragment by lazy { DetailFragment() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        setFragment()
    }
    fun setFragment() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, listFragment)
        transaction.commit()
    }

    fun goDetail() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, detailFragment)
        transaction.addToBackStack("detail")
        transaction.commit()
    }
    fun goBack() {
        onBackPressed()
    }
}
Enter fullscreen mode Exit fullscreen mode

[ListFragment.kt]

class ListFragment : Fragment(R.layout.fragment_list) {
    lateinit var mainActivity:MainActivity
    lateinit var binding: FragmentListBinding

    override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentListBinding.inflate(inflater,container,false)
        binding.btnNext.setOnClickListener { mainActivity?.goDetail()}
        return binding.root
    }
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if(context is MainActivity) mainActivity = context
    }
}
Enter fullscreen mode Exit fullscreen mode

[DetailFragment.kt]

class DetailFragment : Fragment() {
    lateinit var mainActivity:MainActivity
    lateinit var binding: FragmentDetailBinding

    override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentDetailBinding.inflate(inflater,container,false)
        binding.btnback.setOnClickListener { mainActivity?.goBack()}
        return binding.root
    }
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if(context is MainActivity) mainActivity = context
    }
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.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"
    android:visibility="visible"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="Activity"
        android:visibility="visible"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/frameLayout"
        android:name="com.example.myapplication.ListFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2"
        tools:layout="@layout/fragment_list" />

</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

[fragment_detail.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"
    android:background="#FFFFFF"
    android:clickable="true"
    tools:context=".DetailFragment"> 
    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="Detail"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.464"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 
    <Button
        android:id="@+id/btnback"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="BACK"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.458"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3" /> 
</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

[fragment_list.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=".ListFragment"> 
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/title_list"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" /> 
    <Button
        android:id="@+id/btnNext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:text="NEXT"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" /> 
</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

5) Passing values ​​to Fragment
[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    val listFragment by lazy { ListFragment() }
    val detailFragment by lazy { DetailFragment() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        setFragment()
    }
    fun setFragment() {
        // pass value
        val bundle = Bundle()
        bundle.putString("key1", "List Fragment");
        bundle.putInt("key2", 20220226);
        listFragment.arguments = bundle
        //
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, listFragment)
        transaction.commit()
    }

    fun goDetail() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, detailFragment)
        transaction.addToBackStack("detail")
        transaction.commit()
    }
    fun goBack() {
        onBackPressed()
    }
}
Enter fullscreen mode Exit fullscreen mode

[ListFragment.kt]

class ListFragment : Fragment(R.layout.fragment_list) {
    lateinit var binding: FragmentListBinding
    lateinit var mainActivity:MainActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if(context is MainActivity) mainActivity = context
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentListBinding.inflate(inflater,container,false)
        with(binding) {
            arguments?.apply {
                textTitle.text = getString("key1")
                textValue.text = "${getInt("key2") }"
            }
            btnNext.setOnClickListener { mainActivity?.goDetail()}
        }
        return binding.root
    }
}
Enter fullscreen mode Exit fullscreen mode

[fragment_list.xml]

<androidx.constraintlayout.widget.ConstraintLayout
 <TextView android:id="@+id/textView"
<Button android:id="@+id/btnNext"
 <TextView android:id="@+id/textTitle"
</androidx.constraintlayout.widget.ConstraintLayout 
Enter fullscreen mode Exit fullscreen mode

6) Create and deliver the value to Fragment displayed on the screen.
[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
    val listFragment by lazy { ListFragment() }
    val detailFragment by lazy { DetailFragment() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        setFragment()
        binding.btnSend.setOnClickListener{
            listFragment.setValue("Pass Data")
        }

    }
    fun setFragment() {
        // pass value
        val bundle = Bundle()
        bundle.putString("key1", "List Fragment");
        bundle.putInt("key2", 20220226);
        listFragment.arguments = bundle
        //
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, listFragment)
        transaction.replace(R.id.frameLayout, listFragment)
        transaction.commit()
    }

    fun goDetail() {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.add(R.id.frameLayout, detailFragment)
        transaction.addToBackStack("detail")
        transaction.commit()
    }
    fun goBack() {
        onBackPressed()
    }
}
Enter fullscreen mode Exit fullscreen mode

[ListFragment.kt]

class ListFragment : Fragment(R.layout.fragment_list) {
    lateinit var mainActivity:MainActivity
    lateinit var binding: FragmentListBinding
    override fun onAttach(context: Context) {
        super.onAttach(context)
        if(context is MainActivity) mainActivity = context
    }
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        binding = FragmentListBinding.inflate(inflater,container,false)
        with(binding) {
            arguments?.apply {
                textTitle.text = getString("key1")
                textValue.text = "${getInt("key2")}"
            }
            btnNext.setOnClickListener { mainActivity?.goDetail()}
        }
        return binding.root
    }
    fun setValue(value:String) {
        binding.textFromActivity.text = value
    }
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<TextView android:id="@+id/textView2"
<androidx.fragment.app.FragmentContainerView android:id="@+id/frameLayout"
<Button android:id="@+id/btnSend"
</androidx.constraintlayout.widget.ConstraintLayout>
Enter fullscreen mode Exit fullscreen mode

[fragment_list.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<TextView android:id="@+id/textView"
<Button android:id="@+id/btnNext"
<TextView android:id="@+id/textTitle"
<TextView android:id="@+id/textValue"
<TextView android:id="@+id/textFromActivity"
Enter fullscreen mode Exit fullscreen mode

6) Transferring the value from fragment to fragment

[build.gradle]

dependencies { 
    // fragment
    implementation "androidx.fragment:fragment-ktx:1.4.1"
}
Enter fullscreen mode Exit fullscreen mode

[MainActivity.kt]

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
Enter fullscreen mode Exit fullscreen mode

[SenderFragment.kt]

class SenderFragment : Fragment() {
    lateinit var binding:FragmentSenderBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentSenderBinding.inflate(inflater, container, false)
        with(binding) {
            btnYes.setOnClickListener{
                val bundle = bundleOf("senderKey" to "Yes")
                setFragmentResult("request", bundle)
            }
            btnNo.setOnClickListener{
                val bundle = bundleOf("senderKey" to "No")
                setFragmentResult("request", bundle)
            }
        }
        return binding.root
    }
}
Enter fullscreen mode Exit fullscreen mode

[ReceiverFragment.kt]

class ReceiverFragment : Fragment() {
    lateinit var binding:FragmentReceiverBinding
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentReceiverBinding.inflate(inflater, container, false)
        setFragmentResultListener("request") { key, bundle ->
            bundle.getString("senderKey")?.let { value ->
                binding.textView.text = value
            }
        }
        return binding.root
    } 
}
Enter fullscreen mode Exit fullscreen mode

[activity_main.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<androidx.fragment.app.FragmentContainerView
<androidx.fragment.app.FragmentContainerView
</androidx.constraintlayout.widget.ConstraintLayout
Enter fullscreen mode Exit fullscreen mode

[fragment_receiver.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<TextView android:id="@+id/textView"
<androidx.constraintlayout.widget.ConstraintLayout
Enter fullscreen mode Exit fullscreen mode

[fragment_sender.xml]

<androidx.constraintlayout.widget.ConstraintLayout
<Button android:id="@+id/btnYes"
<Button android:id="@+id/btnNo"
</androidx.constraintlayout.widget.ConstraintLayout
Enter fullscreen mode Exit fullscreen mode

Top comments (0)