片段内容在我切换并再次选择之前不会显示

时间:2014-08-18 17:10:56

标签: java android android-fragments

我的Android应用程序出现了问题:我的片段内容在我切换之前不显示,我再次选择它。应该在片段开头加载什么是卡片列表。

在这里你得到了片段的onCreate方法来加载所有内容:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bundle = this.getArguments();
    debts = bundle.getParcelableArrayList("list");
    adapter =  new CardAdapter(getActivity(), android.R.color.holo_blue_dark);

    for (int i=0; i<debts.size();++i) {
        Debt d = debts.get(i);
        Card card = new Card(d.getSecondUser(),d.getSubject());
        adapter.add(card);
    }


}

这里是onActivityCreated方法,我为列表设置了适配器:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    CardListView list = (CardListView) getView().findViewById(R.id.newCard);
    list.setCardTheme(CardTheme.Light);
    list.setAdapter(adapter);
}

如果我使用已经加载的卡的ArrayList,它可以工作,但不是这样。 我几乎尝试了一切......非常感谢你。


更新:即使我尝试了你给我的解决方案,它仍在发生,我的代码现在:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    bundle = this.getArguments();
    debts = bundle.getParcelableArrayList("list");
    adapter =  new CardAdapter(getActivity(), android.R.color.holo_blue_dark);

    for (int i=0; i<debts.size();++i) {
        Debt d = debts.get(i);
        Card card = new Card(d.getSecondUser(),d.getSubject());
        adapter.add(card);
    }


}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_debts, container,
            false);

    CardListView list = (CardListView) rootView.findViewById(R.id.newCard);
    list.setCardTheme(CardTheme.Light);
    list.setAdapter(adapter);

    return rootView;
}

1 个答案:

答案 0 :(得分:0)

您应该在onCreateView()方法中初始化cardListView。在onActivityCreated()方法之前调用onCreateView()。 onCreateView()应该是片段视图初始化时的点。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

    //use your layout file instead of R.layout.fragment_main
    View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

    CardListView list = rootView.findViewById(R.id.newCard);
    list.setCardTheme(CardTheme.Light);
    list.setAdapter(adapter);
}

请查看the lifecycle of Fragments