我在这里找到了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)”
2条答案
按热度按时间cetgtptt1#
您可以像下面这样将service handler作为private成员类移动到您的Activity中,以使用Activity的thiscontext。
字符串
编辑:
型
然后像这样在你的Activity中示例化它:
型
ar7v8xwq2#
我也有同样的问题,我把
runOnUiThread()
替换成了getActivity().runOnUiThread()
。而且成功了