Android - howto pass data to the Runnable in runOnUiThread?(Android - 如何在runOnUiThread 中将数据传递给Runnable?)
问题描述
我需要更新一些 UI 并在 UI 线程内使用 runOnUiThread
现在 UI 的数据来自另一个线程,这里用 data
表示.
I need to update some UI and do it inside of the UI thread by using runOnUiThread
Now the data for the UI comes from the other Thread, represented by data
here.
如何将数据传递给 Runnable,以便它们可用于更新 UI?Android 似乎不允许直接使用数据.有没有优雅的方法来做到这一点?
How can i pass the data to the Runnable, so tht they can be used to update the UI? Android doesn't seem to allow using data directly. Is there an elegant way to do this?
public void OnNewSensorData(Data data) {
runOnUiThread(new Runnable() {
public void run() {
//use data
}
});
}
我的解决方案是在可运行文件中创建一个字段private Data sensordata
,并为其分配数据.这仅适用于原始 Data data
是最终的.
My solution was creating a fioeld private Data sensordata
inside of the runnable, and assigning data to it. This works only, if the original Data data
is final.
public void OnNewSensorData(final Data data) {
runOnUiThread(new Runnable() {
private Data sensordata = data;
public void run() {
//use sensordata which is equal to data
}
});
}
推荐答案
你发现的问题是
Java 中的内部类捕获(关闭")其中的词法范围它们被定义.但它们只捕获声明为最终"的变量.
Inner classes in Java capture ("close over") the lexical scope in which they are defined. But they only capture variables that are declared "final".
如果这很清楚,这里有一个很好的细节讨论:不能参考到在不同方法中定义的内部类中的非最终变量
If this is clear as mud, there's a good discussion of the details here: Cannot refer to a non-final variable inside an inner class defined in a different method
但是您的解决方案看起来不错.此外,如果 data
是最终的,您可以将代码简化为:
But your solution looks fine. In addition, provided that data
is final, you could simplify the code to this:
public void OnNewSensorData(final Data data) {
runOnUiThread(new Runnable() {
public void run() {
// use data here
data.doSomething();
}
});
}
这篇关于Android - 如何在runOnUiThread 中将数据传递给Runnable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android - 如何在runOnUiThread 中将数据传递给Runnable?
基础教程推荐
- Kivy Buildozer 无法构建 apk,命令失败:./distribute.sh -m “kivy"d 2022-01-01
- 如何在 iPhone 上显示来自 API 的 HTML 文本? 2022-01-01
- 如何在没有IB的情况下将2个按钮添加到右侧的UINavigationbar? 2022-01-01
- Android:对话框关闭而不调用关闭 2022-01-01
- 在 gmail 中为 ios 应用程序检索朋友的朋友 2022-01-01
- 当从同一个组件调用时,两个 IBAction 触发的顺序是什么? 2022-01-01
- UIWebView 委托方法 shouldStartLoadWithRequest:在 WKWebView 中等效? 2022-01-01
- 如何在 UIImageView 中异步加载图像? 2022-01-01
- android 应用程序已发布,但在 google play 中找不到 2022-01-01
- 如何让对象对 Cocos2D 中的触摸做出反应? 2022-01-01