kotlinandroid-activityfragmentandroid-fragmentactivity

Change Activity to Fragment


I started a project using Activity however now I need it to be a Fragment because I want to use a Bottom Navigation Bar. How do I go about doing this? I'm new to Android development and I'm stuck. Any help would be appreciated.

class CalculatorOZ : AppCompatActivity() {

    private lateinit var binding: FragmentCalculatorBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = FragmentCalculatorBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btnGo.setOnClickListener {
            val df = DecimalFormat("#.#", DecimalFormatSymbols(Locale.ENGLISH))


            var firstValue = binding.etContainerSizeOz.text.toString().toFloat()
            var secondValue = binding.etDilutionRatio.text.toString().toFloat() + 1

            val totalProduct: Double = String.format("%.0f", firstValue / secondValue).toDouble()

            val totalWater: Double = String.format("%.0f", firstValue - totalProduct).toDouble()

            binding.tvTotalProduct.text = totalProduct.toString()
            binding.tvTotalWater.text = totalWater.toString()
        }
    }
}

Solution

  • You must need to understand the basic of fragment and activity in android. Activity will work as the container where the fragments are placed. You can't change the activity to fragment as in basic terms activity will be the parent and fragment will be the child of it.

    Make sure to understand the lifecycle of the activity and fragment as well to understand in detail about the fragment and it's behavior with the activity.

    Here is the link for the demonstration of the fragment attachment over the activity.