I have a simple android app, which is changing text and color of TextView depends on how much passengers i added. I want to create a sealed class for each state.
Here is the code of the current app:
class MainActivity : AppCompatActivity() {
private var counter = 0
private val maxPassengers = 50
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
binding = ActivityMainBinding.inflate(layoutInflater)
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.seats.text = counter.toString()
binding.minusButton.setOnClickListener {
counter -= 1
checkAndSwitchState(counter)
}
binding.plusButton.setOnClickListener {
counter = 1
checkAndSwitchState(counter)
}
binding.resetButton.setOnClickListener {
counter = 0
it.visibility = View.GONE
checkAndSwitchState(counter)
}
}
private fun checkAndSwitchState(counter: Int) {
if (counter == 0) {
binding.minusButton.isEnabled = false
binding.textView.text = binding.textView.context.getText(R.string.green_text)
binding.textView.setTextColor(Color.parseColor("#00FF00"))
binding.seats.text = counter.toString()
}
if (counter in 1 until maxPassengers) {
binding.minusButton.isEnabled = true
binding.textView.text = "Осталось мест: " "${maxPassengers - counter}"
binding.textView.setTextColor(Color.parseColor("#0000FF"))
binding.seats.text = counter.toString()
}
if (counter >= maxPassengers) {
binding.resetButton.visibility = View.VISIBLE
binding.textView.text = binding.textView.context.getText(R.string.red_text)
binding.textView.setTextColor(Color.parseColor("#FF0000"))
binding.seats.text = counter.toString()
}
}
}
So the question is how can i use binding outside MainActivity in sealed class
CodePudding user response:
you can refer this link mentioned below for binding views with Sealed class.