当屏幕方向改变时,我对fragment有问题。
在我的代码中,我根据屏幕方向创建了不同的布局xml。
例如,布局目录中有header_landscape.xml和header_rapital.xml。在线性布局中,每个不同的报头都有相同的片段。所以当我转动我的设备时,我有一个错误“重复ID…”对应于我的片段。
布局的不同在于内容,当我在“横向”时,我显示的信息比在“纵向”中显示的信息要多。
创建我的活动时:
setContentView(R.layout.main_landscape);
//header
date=(TextView)findViewById(R.id.headerLandscapeDate);
routeSens=(TextView) findViewById(R.id.headerLandscapeRouteSens);
pkHeader=(TextView) findViewById(R.id.headerLandscapePk);
//Récupération de la listview créée dans le fichier main.xml
maListViewPerso = (ListView) findViewById(R.id.ListeChoix);
//On attribut à notre listView l'adapter que l'on vient de créer
maListViewPerso.setAdapter(chargeMenu());
$方向屏幕更改时修改布局的代码。
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE && isLoaded && oldScreenStateOrientation!=newConfig.orientation)
{
setContentView(R.layout.main_landscape);
//header
date=(TextView)findViewById(R.id.headerLandscapeDate);
routeSens=(TextView) findViewById(R.id.headerLandscapeRouteSens);
pkHeader=(TextView) findViewById(R.id.headerLandscapePk);
maListViewPerso = (ListView) findViewById(R.id.ListeChoix);
//On attribut à notre listView l'adapter que l'on vient de créer
maListViewPerso.setAdapter(chargeMenu());
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT && isLoaded && oldScreenStateOrientation!=newConfig.orientation)
{
setContentView(R.layout.main_portrait);
routeSens=(TextView) findViewById(R.id.headerPortraitRouteSens);
pkHeader=(TextView) findViewById(R.id.headerPortraitPk);
maListViewPerso = (ListView) findViewById(R.id.ListeChoix);
//On attribut à notre listView l'adapter que l'on vient de créer
maListViewPerso.setAdapter(chargeMenu());
}
}
如果有人有办法的话。
我开发了API8(兼容性库片段)。
对不起我的英语。
谢谢
最佳答案
你应该让安卓为你做所有的配置切换!不要在“onconfigurationchanged”中执行任何操作,甚至从清单中删除所有配置更改!
把你的肖像布局
布局/文件夹
把你的景观布局
布局区域/文件夹
确保它们都被命名为:main.xml(或者任何东西,只要它是相同的)
然后在activity.oncreate中,执行以下操作:
// Will automatically select the correct layout
setContentView(R.layout.main);
//header
// If this is in portrait, date will be null. Check for that later
date=(TextView)findViewById(R.id.headerDate);
routeSens=(TextView) findViewById(R.id.headerRouteSens);
pkHeader=(TextView) findViewById(R.id.headerPk);
//Récupération de la listview créée dans le fichier main.xml
maListViewPerso = (ListView) findViewById(R.id.ListeChoix);
//On attribut à notre listView l'adapter que l'on vient de créer
maListViewPerso.setAdapter(chargeMenu());
这样,您就可以让android担心使用哪种配置。如果只想在大屏幕上显示横向视图,可以将其放在layout-w1024dp等文件夹中。这样你可以很容易地拥有多个布局。