我想创建 ListView ,它每 4 秒添加一个项目并将焦点设置在最后一个项目上。问题是我的片段等待异步任务结束了,然后才显示(所有时间异步任务都在白屏工作)
public class LogFragment extends SherlockFragment {
private ListView lvList;
private ArrayAdapter<String> adapter;
private UpdateTask mTask = null;
String[] values = new String[] { "Android", "iPhone", "WindowsMobile" };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.log_fragment, container, false);
lvList = (ListView) view.findViewById(R.id.lvLog);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
adapter = new ArrayAdapter<String>(getSherlockActivity(),
android.R.layout.simple_list_item_1, list);
lvList.setAdapter(adapter);
return view;
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d("myLogs", "LogFragment:OnCreate");
mTask = new UpdateTask();
super.onCreate(savedInstanceState);
mTask.execute();
}
还有我的 AnyncTask:
public class UpdateTask extends AsyncTask<Void, Void, Void> {
int temp = 10;
protected Void doInBackground(Void... params) {
getSherlockActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
while (temp-- > 0) {
try {
TimeUnit.SECONDS.sleep(4);
adapter.add("Lol" + String.valueOf(temp));
lvList.setSelection(lvList.getAdapter().getCount() - 1);
Log.d("myLogs", "Added from Async");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
return null;
}
protected void onPostExecute(String result) {
}
}
如何解决我的问题?