关于使用 'liveData.observe' 的问题
Questions about using 'liveData.observe'
我正在自学 Android 开发。我以为我已经明白 what/how 'liveData.observe' 工作了。但是...
制作一个简单的小应用程序,用于侦听来自蓝牙设备的输入,并根据该蓝牙输入显示或隐藏图像。
我已经完成了所有工作,但现在我想添加另一个功能,我 运行 撞墙了。该功能是在每次 liveData.Observe returns TRUE 时增加一个计数器。
要么我不明白'liveData.observe',要么我试图错误地使用它(可能是这两种情况)。
我现在正在开发一个函数来增加这个计数器,这是我被挂断的地方。我目前的想法是创建一个单独的函数(pigCounter())。但我一事无成。
onCreate
class MainActivity : AppCompatActivity() {
private var liveData: MutableLiveData<String> = MutableLiveData()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
<SNIP>
...
</SNIP>
liveData.observe(this, androidx.lifecycle.Observer {
imageView_mothership_LED_state.showOrHideImage(it == "1")
})
pigCounter()
}
以下来自activity_main.xml
imageView_mothership_LED_state
<ImageView
android:id="@+id/imageView_mothership_LED_state"
android:layout_width="124dp"
android:layout_height="144dp"
android:scaleType="fitCenter"
android:soundEffectsEnabled="false"
app:layout_constraintBottom_toBottomOf="@+id/imageView_blueYesOrNo"
app:layout_constraintEnd_toEndOf="@+id/imageView_blueYesOrNo"
app:layout_constraintStart_toStartOf="@+id/imageView_blueYesOrNo"
app:layout_constraintTop_toTopOf="@+id/imageView_blueYesOrNo"
app:srcCompat="@drawable/ic_check_black_24dp"
android:contentDescription="Check mark image to indicate if LED is on/off" />
下面是设置图片可见性的函数
showOrHideImage()
// display or don't display check mark image
private fun View.showOrHideImage(imageShow: Boolean) {
visibility = if (imageShow) View.VISIBLE else View.GONE
}
这是处理传入蓝牙数据的函数。
readBlueToothDataFromMothership()
private fun readBlueToothDataFromMothership(bluetoothSocket: BluetoothSocket) {
Log.i(LOGTAG, Thread.currentThread().name)
val bluetoothSocketInputStream = bluetoothSocket.inputStream
val buffer = ByteArray(1024)
var bytes: Int
//Loop to listen for received bluetooth messages
while (true) {
try {
bytes = bluetoothSocketInputStream.read(buffer)
val readMessage = String(buffer, 0, bytes)
liveData.postValue(readMessage)
} catch (e: IOException) {
e.printStackTrace()
break
}
}
这是我正在编写的函数,因为我想每次都增加一个计数器。
猪数
private fun pigCount() {
var count = 0
var counterTextView = findViewById<TextView>(R.id.textView_blueCounter)
if(imageView_mothership_LED_state.showOrHideImage(true)) {
counterTextView.text = count.toString()
count++
}
由于类型不匹配(期望布尔值,得到单位),这不起作用。我也试过将它移到 onCreate() 中的 liveData.observe 函数中。但同样的障碍。
任何人都可以指出我正确的方向。我有一种偷偷摸摸的感觉,我在这方面还差得远。并且会很感激。 :)
要计算 LiveData
returns true
的次数非常简单,您可以使用 MediatorLiveData
.
假设你有一个合适的LiveData<Boolean>
,你可以这样做:
val trueFalse = MutableLiveData<Boolean>()
val counter by lazy {
MediatorLiveData<Int>().apply {
value = 0 // Initialize the counter
// Add the trueFalse as a source of this live data
addSource(trueFalse) { boolVal ->
if(boolVal == true) {
// If the mediator live data had a value, use it, if null use 0; and add +1 to it because the boolVal was true
value = (value ?: 0) + 1
}
}
}
}
/* Somewhere else in the code */
fun setupTextView() {
counter.observe({lifecycle}) {
val tv = findViewById<TextView>(R.id.tv_something)
tv.text = "$it"
}
}
这将创建一个 MediatorLiveData
,它将 trueFalse 实时数据作为源。
如果值为 true
将继续并 post counter
实时数据中的新值。
我正在自学 Android 开发。我以为我已经明白 what/how 'liveData.observe' 工作了。但是...
制作一个简单的小应用程序,用于侦听来自蓝牙设备的输入,并根据该蓝牙输入显示或隐藏图像。
我已经完成了所有工作,但现在我想添加另一个功能,我 运行 撞墙了。该功能是在每次 liveData.Observe returns TRUE 时增加一个计数器。
要么我不明白'liveData.observe',要么我试图错误地使用它(可能是这两种情况)。
我现在正在开发一个函数来增加这个计数器,这是我被挂断的地方。我目前的想法是创建一个单独的函数(pigCounter())。但我一事无成。
onCreate
class MainActivity : AppCompatActivity() {
private var liveData: MutableLiveData<String> = MutableLiveData()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
<SNIP>
...
</SNIP>
liveData.observe(this, androidx.lifecycle.Observer {
imageView_mothership_LED_state.showOrHideImage(it == "1")
})
pigCounter()
}
以下来自activity_main.xml
imageView_mothership_LED_state
<ImageView
android:id="@+id/imageView_mothership_LED_state"
android:layout_width="124dp"
android:layout_height="144dp"
android:scaleType="fitCenter"
android:soundEffectsEnabled="false"
app:layout_constraintBottom_toBottomOf="@+id/imageView_blueYesOrNo"
app:layout_constraintEnd_toEndOf="@+id/imageView_blueYesOrNo"
app:layout_constraintStart_toStartOf="@+id/imageView_blueYesOrNo"
app:layout_constraintTop_toTopOf="@+id/imageView_blueYesOrNo"
app:srcCompat="@drawable/ic_check_black_24dp"
android:contentDescription="Check mark image to indicate if LED is on/off" />
下面是设置图片可见性的函数
showOrHideImage()
// display or don't display check mark image
private fun View.showOrHideImage(imageShow: Boolean) {
visibility = if (imageShow) View.VISIBLE else View.GONE
}
这是处理传入蓝牙数据的函数。
readBlueToothDataFromMothership()
private fun readBlueToothDataFromMothership(bluetoothSocket: BluetoothSocket) {
Log.i(LOGTAG, Thread.currentThread().name)
val bluetoothSocketInputStream = bluetoothSocket.inputStream
val buffer = ByteArray(1024)
var bytes: Int
//Loop to listen for received bluetooth messages
while (true) {
try {
bytes = bluetoothSocketInputStream.read(buffer)
val readMessage = String(buffer, 0, bytes)
liveData.postValue(readMessage)
} catch (e: IOException) {
e.printStackTrace()
break
}
}
这是我正在编写的函数,因为我想每次都增加一个计数器。
猪数
private fun pigCount() {
var count = 0
var counterTextView = findViewById<TextView>(R.id.textView_blueCounter)
if(imageView_mothership_LED_state.showOrHideImage(true)) {
counterTextView.text = count.toString()
count++
}
由于类型不匹配(期望布尔值,得到单位),这不起作用。我也试过将它移到 onCreate() 中的 liveData.observe 函数中。但同样的障碍。
任何人都可以指出我正确的方向。我有一种偷偷摸摸的感觉,我在这方面还差得远。并且会很感激。 :)
要计算 LiveData
returns true
的次数非常简单,您可以使用 MediatorLiveData
.
假设你有一个合适的LiveData<Boolean>
,你可以这样做:
val trueFalse = MutableLiveData<Boolean>()
val counter by lazy {
MediatorLiveData<Int>().apply {
value = 0 // Initialize the counter
// Add the trueFalse as a source of this live data
addSource(trueFalse) { boolVal ->
if(boolVal == true) {
// If the mediator live data had a value, use it, if null use 0; and add +1 to it because the boolVal was true
value = (value ?: 0) + 1
}
}
}
}
/* Somewhere else in the code */
fun setupTextView() {
counter.observe({lifecycle}) {
val tv = findViewById<TextView>(R.id.tv_something)
tv.text = "$it"
}
}
这将创建一个 MediatorLiveData
,它将 trueFalse 实时数据作为源。
如果值为 true
将继续并 post counter
实时数据中的新值。