我想要在 onProgressChanged 方法之外使用 seekbar 值但它总是给我一个零值。我想取两个搜索栏的值并将它们相乘
class BmiActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
var weight =0f
var height = 0f
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_bmi)
val seekbarHeight=findViewById<SeekBar>(R.id.seekBarHeight)
var tvResultHeight=findViewById<TextView>(R.id.textViewResultHeight)
val tvResultWeight=findViewById<TextView>(R.id.textViewResultWeight)
val seekbarWeight =findViewById<SeekBar>(R.id.seekBarWeight)
val spinnerAge=findViewById<Spinner>(R.id.spinnerAge)
val imageviewNeedle=findViewById<ImageView>(R.id.imageViewNeedle)
val tvResultBmi=findViewById<TextView>(R.id.textViewResultBmi)
seekbarHeight.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvResultHeight.text=" "+progress.toString()
height= progress.toFloat()
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
seekbarWeight.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvResultWeight.text=" "+progress.toString()
weight=progress.toFloat()
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
var result = weight/(height*height)
tvResultBmi.text=result.toString()
答案 0 :(得分:0)
你可以做回调/接口。然后当两者都触发时,值发生了变化。
首先,您需要创建界面。创建一个名为 ResultInterface.kt 的新文件
interface ResultInterface {
fun onValueChanged(height: Float, weight: Float)
}
然后将它们中的每一个放入一个函数中。
fun seekBarHeight(resultInterface: ResultInterface) {
seekbarHeight.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvResultHeight.text = " " + progress.toString()
val height = progress.toFloat()
resultInterface.onValueChanged(height, 0f)
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
}
fun seekBarWeight(resultInterface: ResultInterface) {
seekbarWeight.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvResultWeight.text = " " + progress.toString()
val weight = progress.toFloat()
resultInterface.onValueChanged(0f, weight)
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
}
})
}
最后,在您的活动中,实施 ResutInterface
class BmiActivity : AppCompatActivity(), ResultInterface {
之后你需要 alt + enter 。并且 onValueChanged
方法将覆盖。
override fun onValueChanged(height: Float, weight: Float) {
val result = weight/(height*height)
tvResultBmi.text=result.toString()
}