旋转时碎片消失 [英] Fragments disappear when rotated
问题描述
我已经使用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
时都添加Fragment
; FragmentManager
会自动维护它们.您应该在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屋!