使用片段时未显示数据

时间:2013-12-29 11:29:26

标签: android android-fragments

我正在使用带有操作栏的视图寻呼机。

此操作栏包含3个标签。

其中一个是players,我称之为:

@Override
        public Fragment getItem(int arg0) {
            switch (arg0) {
            case 0:
                return new TeamInformation();
            case 1:
                return new TeamPlayers();
            default:
                return new TeamInformation();
            }
        }

TeamPlayers类是:

public class TeamPlayers extends Fragment {

    private ListView lv_players;
    private TeamPlayersAdapter adapter;
    private List<Player> players = new LinkedList<Player>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.team_players, container, false);
        lv_players = (ListView) v.findViewById(R.id.lv_players);
        adapter = new TeamPlayersAdapter(this.getActivity(), players);
        lv_players.setAdapter(adapter);
        new getTeamPlayers().execute(1);
        return v;
    }

当我打电话给这个屏幕时,我什么都没有,我的意思是没有任何数据显示,但是,如果你注意到我打电话给getTeamPlayers,那就是:

private class getTeamPlayers extends
            AsyncTask<Integer, Integer, List<Player>> {

        @Override
        protected List<Player> doInBackground(Integer... params) {
            List<Player> players = new LinkedList<Player>();
            Player player = new Player();
            player.setID(1);
            player.setEn_name("Totti");
            players.add(player);
            player = new Player();
            player.setID(2);
            player.setEn_name("De Rossi");
            players.add(player);
            return players;
        }

        @Override
        protected void onPostExecute(List<Player> result) {
            super.onPostExecute(result);
            players = new LinkedList<Player>();
            players.addAll(result);
            adapter.notifyDataSetChanged();
        }

    }

看我把数据放进去。我做一个日志来检查应用程序是否调用了onCreateView,我可以看到日志。

帮助赞赏

2 个答案:

答案 0 :(得分:1)

加载列表时设置适配器意味着在postExecute

@Override
protected void onPostExecute(List<Player> result) {
    super.onPostExecute(result);
    players = new LinkedList<Player>();
    players.addAll(result);
    adapter = new TeamPlayersAdapter(this.getActivity(), players);
    lv_players.setAdapter(adapter);
}

答案 1 :(得分:0)

这可能对您有所帮助......无需多次将适配器设置为ListView ...

    @Override
    protected void onPostExecute(List<Player> result) {
        if(result != null) {
           players.clear();
           players.addAll(result);
           adapter.notifyDataSetChanged();
        }
    }