我找到了 this这里有一个关于如何使用 runOnUiThread
方法的示例,但我不明白如何使用它。
我在主要 Activity 中设置了列表适配器
// 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;
}
但是我在运行时遇到了这个错误
Only the original thread that created a view hierarchy can touch its views.
所以我尝试用.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;
});
}
但是我明白了
Cannot resolve method 'runOnUiThread(anonymous Java.lang.runnable)'
最佳答案
您可以将服务处理程序作为 private 成员类移动到您的 Activity 中,如下所示,以使用 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
}
然后像这样在您的 Activity 中实例化它:
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();
}
}
关于android - 无法解析方法 .runOnUiThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33979132/