旋转后更改布局无法更新ListView

时间:2013-10-19 23:21:19

标签: android android-listview android-fragments

我有一个ListView和ArrayAdapter的片段作为自定义片段类中的全局变量。我还有一个应该更新此列表的功能,使其他文本字段可见或不可见。因此,如果我在活动后旋转(更改为特殊的土地布局)后调用列表更新功能,我发现ListView和ArrayAdapter对象为空。因此我无法更新我的列表。我该怎么办? Thnx家伙。

    private View fragmentView;
    private SimpleListNewsAdapter adapterNews;
    private ListView listNews;

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

        fragmentView = inflater.inflate(getLayoutId(), container, false);
        listNews = (ListView) fragmentView.findViewById(R.id.newsList); 
        adapterNews = new SimpleListNewsAdapter(fragmentView.getContext(), R.id.newsList);
        listNews.setAdapter(adapterNews);
        …
        return fragmentView;
    }

    public void showListExpanded(Boolean expanded){
        if (isShowDesc != expanded){
            isShowDesc = expanded;

            if (adapterNews != null && listNews != null){
                adapterNews.notifyDataSetChanged();             
                listNews.refreshDrawableState();
                listNews.invalidateViews();
                listNews.setAdapter(adapterNews);

            } else {
                // Here I should do something to refresh my list
            }
        }
    } 

2 个答案:

答案 0 :(得分:1)

当您旋转设备时(如果您未在清单中声明android:configChanges =“orientation”),您的活动将被重新创建。我猜你没有正确地在你的onCreate方法上初始化你的listView和你的适配器(可能你正在等待用户交互,比如按钮点击)。 如果您分享完整的代码,您可以得到答案:)

答案 1 :(得分:0)

我的错误是在活动中从FragmentPagerAdapter.getItem创建一个新的空片段对象,然后调用showListExpanded。我通过在创建时刻的原始片段的簿记链接来解决这个问题。我使用了good example