【发布时间】:2016-04-27 19:19:57
【问题描述】:
我是编程新手,我有一个带有片段的导航抽屉。当我旋转我的设备时,它会“重新启动应用程序”或调用 Home 片段。我不确定如何解决这个问题,因为它与 super.onCreate (savedInstance) 有关,但还没有找到如何实现它。我还尝试在清单上使用 onConfigurationChanged 方法,但没有成功。我一直在从不同的教程中复制代码以使我的应用程序正常工作,所以我不确定我发布的代码是否应该是我应该发布的代码。谢谢。
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
ImageView home;
Fragment fragment = null;
TextView appname;
ExpandableListView expListView;
HashMap<String, List<String>> listDataChild;
ExpandableListAdapter listAdapter;
List<String> listDataHeader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String fontPath = "neue.ttf";
setContentView(R.layout.activity_main);
home = (ImageView)findViewById(R.id.home);
home.setOnClickListener(homeOnclickListener);
appname = (TextView)findViewById(R.id.appname);
Typeface tf = Typeface.createFromAsset(this.getAssets(), fontPath);
appname.setTypeface(tf);
setUpDrawer();
}
private void setUpDrawer() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setScrimColor(getResources().getColor(android.R.color.transparent));
mDrawerLayout.setDrawerListener(mDrawerListener);
expListView = (ExpandableListView) findViewById(R.id.lvExp);
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
fragment = new Home();
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerLayout.closeDrawer(expListView);
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
switch (groupPosition) {
case 0:
switch (childPosition) {
case 0:
fragment = new 1();
break;
case 1:
fragment = new 2();
break;
case 2:
fragment = new 3();
break;
...
}
break;
case 1:
switch (childPosition) {
case 0:
fragment = new 4();
break;
...
default:
break;
}
break;
...
}
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerLayout.closeDrawer(expListView);
return false;
}
});
}...
【问题讨论】:
-
在您的清单文件中添加
android:configChanges="orientation"到您的活动标签。这可以防止 Activity 在方向更改时再次破坏和创建。此外,让您的 Activity 从支持库中扩展 AppCompatActivity;这是一种更好的向后兼容性方法,将确保 configeChanges 标记能够正常工作。 -
谢谢我试过了,但没用
-
正如 Shadab Ansari 所回答的那样,这个答案对我有很大帮助,但我不得不解决其他问题,最后我找到了一种解决旋转问题的方法,它不会让我的应用程序崩溃,如果你想要的话看这里stackoverflow.com/questions/36900671/…
标签: android android-fragments orientation screen-rotation savestate