我在这里找到了关于如何使用.getParents()
方法的this例子,但我不明白如何使用它。
我在主要活动中设置了列表适配器
runOnUiThreaed
我在这里调用服务处理程序类
的列表适配器 // 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();
}
类中的.run()
方法,其中我更新了列表和列表适配器
ServiceHandler
但是我在运行时出现了这个错误
只有创建视图层次结构的原始线程才能触及其视图。
所以我尝试用public void run(Adapter listAdapter, ArrayList<String> list){
// some code
list[0] = "foo";
listAdapter.notifyDataSetChanged;
}
所以这里.runOnUiThread
类的.run()
方法再次出现ServiceHandler
runOnUiThread
但是我得到了
无法解析方法&#39; runOnUiThread(匿名Java.lang.runnable)&#39;
答案 0 :(得分:12)
您可以将服务处理程序作为私有成员类移动到您的活动中,如下所示,以使用Activity的 this 上下文。
class MyActivity extends Activity {
private class ServiceHandler /** Whichever class you extend */ {
public void run() {
MyActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
}
private MyListAdapterTracks mAdapter;
private ServiceHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Some code
mAdapter = new MyListAdapterTracks(getActivity(), R.layout.item_layout, list);
listView.setAdapter(mAdapter);
// Some code
ServiceHandler sh = new ServiceHandler();
sh.run();
}
}
编辑:
public class ServiceHandler /** Whichever class you extend */ {
private final Activity mActivity;
private final MyListAdapterTracks mAdapter;
public ServiceHandler(Activity activity, MyListAdapterTracks adapter) {
mActivity = activity;
mAdapter = adapter;
}
@Override
public void run() {
mActivity.runOnUiThread(new Runnable() {
@Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
}
// More code
}
然后在你的活动中实现它:
class MyActivity extends Activity {
private MyListAdapterTracks mAdapter;
private ServiceHandler mHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Some code
ServiceHandler sh = new ServiceHandler(this);
sh.run();
}
}
答案 1 :(得分:0)
我遇到了同样的问题,我将runOnUiThread()
替换为getActivity().runOnUiThread()
。而且有效。