【发布时间】:2020-06-09 01:54:05
【问题描述】:
我在这里找到了this 示例,了解如何使用runOnUiThread 方法,但我不明白如何使用它。
我在我的主要活动中设置了列表适配器
// Set a gobal reference to the list adapter and the list respectivly
ListAdapter listAdapter;
static ArrayList<String> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// some code
adapter = new ListAdapter(getActivity(), R.layout.item_layout, list);
listView.setAdapter(adapter);
// some code
}
我这里的列表适配器调用了一个服务处理程序类
public class ListAdapter {
// some code
ServiceHandler sh = new ServiceHandler();
sh.run();
}
这是ServiceHandler 类中的.run() 方法,我在其中更新了列表和列表适配器
public void run(Adapter listAdapter, ArrayList<String> list){
// some code
list[0] = "foo";
listAdapter.notifyDataSetChanged;
}
但我在运行时收到此错误
只有创建视图层次结构的原始线程才能接触其视图。
所以我尝试用.runOnUiThread解决错误
所以这里又是ServiceHandler 类中的.run() 方法,runOnUiThread
public void run(Adapter listAdapter, ArrayList<String> list){
// some code
runOnUiThread(new Runnable() {
@Override
public void run() {
list[0] = "foo";
listAdapter.notifyDataSetChanged;
});
}
但我明白了
无法解析方法'runOnUiThread(anonymous Java.lang.runnable)'
【问题讨论】: