旋转时碎片消失 [英] Fragments disappear when rotated

查看:113
本文介绍了旋转时碎片消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用Java添加了片段.

I’ve added the fragments using java.

当我以纵向模式打开该应用程序时,它会起作用.

when I open the app in portrait mode it works.

如果我旋转片段,片段就会消失.

if I rotate the fragment just disappear.

但是,如果我关闭应用程序,然后旋转手机,然后再次打开应用程序,则它可以正常工作.

but if I close the app, then rotate the phone, and then open the app again, it works.

我有两种不同的布局,一种是纵向模式,另一种是横向模式, 两者具有相同的名称,我在布局"文件夹中具有肖像的布局,而在布局-土地"文件夹中具有风景的布局.

i have two different layouts one for portrait mode other for landscape mode, both with the same name, i have the layout for portrait in the "layout" folder, and the layout for landscape on "layout-land" folder.

似乎我忘记了一些东西,真诚的我是android开发的新手.

it seems like i am forgetting something, sincerely i am new on android development.

活动:

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ListFragment frag = new ListFragment();

        setContentView(R.layout.layout_main);

        FragmentManager manager = getFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();

        transaction.add(R.id.LIST_LAYOUT,frag,"LIST");
        transaction.commit();

    }

片段:

public class ListFragment extends Fragment implements AdapterView.OnItemClickListener{


    ListView List;
    Communicator communicator;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        //return super.onCreateView(inflater, container, savedInstanceState);

        return inflater.inflate(R.layout.mlistfragment,container,false);


    }

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

        communicator = (Communicator) getActivity();

        List = (ListView) getActivity().findViewById(R.id.listView);

        ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),R.array.StrListButtons,android.R.layout.simple_list_item_1);
        List.setAdapter(adapter);


        List.setOnItemClickListener(this);


    }

推荐答案

实际上,不必每次创建Activity时都添加FragmentFragmentManager会自动维护它们.您应该在if (savedInstanceState == null)检查中包装执行FragmentTransaction的代码,以便仅在第一次创建Activity时执行该代码.例如:

You actually don't need to add the Fragment every time the Activity is created; the FragmentManager maintains them automatically. You should wrap the code which does the FragmentTransaction in an if (savedInstanceState == null) check, so that it is only executed the first time the Activity is created. For example:

if (savedInstanceState == null) {
    getFragmentManager().beginTransaction()
                        .add(R.id.list_layout, new ListFragment(), "LIST")
                        .commit();
}

这篇关于旋转时碎片消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆