Android asynctask 无法在异步任务的PostExecute上更改listview颜色
我无法更改异步任务onPostExecute中listview项的颜色Android asynctask 无法在异步任务的PostExecute上更改listview颜色,android-asynctask,Android Asynctask,我无法更改异步任务onPostExecute中listview项的颜色 final int color = 0xAA8D75B0; private class ClientAsync extends AsyncTask<String, Void, String> { // some code here ... protected void onPostExecute(String res) { ArrayAdapter<String> adapter = new
final int color = 0xAA8D75B0;
private class ClientAsync extends AsyncTask<String, Void, String> {
// some code here ...
protected void onPostExecute(String res) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, mylist);
lv.setAdapter(adapter);
int n = lv.getCount();
for (int i=0; i<n; i++){
lv.getChildAt(i).setBackgroundColor(color);
}
}
我在运行时遇到空指针异常。但是,当我尝试更改按钮onClickListener中的颜色时,效果很好。为什么?试试这个
Runnable color = new Runnable(){
@Override
public void run() {
...
your code to change color here
...
}
};
lv.postDelayed(color, 1000);
您应该在ui线程中运行代码,以避免出现nullpointerexception。因此,只要尝试一下,它就会解决您的问题,假设您的AsyncTask是活动的内部类:
private class ClientAsync extends AsyncTask<String, Void, String> {
// some code here ...
protected void onPostExecute(String res) {
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, mylist);
lv.setAdapter(adapter);
int n = lv.getCount();
for (int i=0; i<n; i++){
runOnUiThread(new Runnable() {
public void run(){
lv.getChildAt(i).setBackgroundColor(color);
}
});
}
}
}
你的代码不起作用。我想如果它在doInBackground内部,那么只需要runOnUiThread,对吗?这段代码最初是有效的,但当项目编号大于10时,我会再次出现空指针异常。