我无法更改异步任务onPostExecute中列表视图项的颜色
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按钮内的颜色时,它工作正常。为什么呢?
答案 0 :(得分:0)
试试这个......
Runnable color = new Runnable(){
@Override
public void run() {
...
your code to change color here
...
}
};
lv.postDelayed(color, 1000);
答案 1 :(得分:0)
您应该在ui-thread中运行代码以避免nullpointerexception。所以试试这个就会解决你的问题(假设你的AsyncTask是一个Activity的内部类):
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);
}
});
}
}
}