-1

我想创建 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) {
            // Add code that loops through JSONArray and adds to adapter here

        }
    }

如何解决我的问题?

4

1 回答 1

1

调用notifyDataSetChanged()来更新 Adapter 中的数据,这将更新 ListView 中显示的内容。此外,从 doInBackground 调用 runOnUiThread 是一个坏主意,该方法旨在执行 UI 线程之外的所有繁重工作,而 onPostExecute 旨在在您的任务执行完成后对 UI 进行更改......我建议下列的 :

protected Void doInBackground(Void... params) {
    TimeUnit.SECONDS.sleep(4);
    adapter.add("Lol" + String.valueOf(temp));
    Log.d("myLogs", "Added from Async");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

protected void onPostExecute(String result) {
    // Add code that loops through JSONArray and adds to adapter here
    lvList.setSelection(lvList.getAdapter().getCount() - 1);
    adapter.notifyDataSetChanged();
}
于 2013-11-09T20:38:54.753 回答