我有一个简单的Android应用程序,这是改变文本和颜色的TextView取决于我添加了多少乘客。我想为每个国家创建一个密封类。
下面是当前应用程序的代码:
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()
}
}
}
因此,问题是如何在密封类中的MainActivity外部使用绑定
1条答案
按热度按时间u4vypkhs1#
你可以参考下面提到的链接来绑定视图和Sealed类。
https://lucianoluzzi.medium.com/android-databinding-ui-states-with-kotlins-sealed-classes-fcf031b514fc