简体   繁体   English

Android布局在横向和纵向上具有不同的项目

[英]Android layout with different items on landscape and on portrait

I have main.xml in res/layout-land and in res/layout. 我在res / layout-land和res / layout中都有main.xml。 There's a grid of 12 icons, 3 by 4 (width, height, respectively). 有一个由12个图标组成的网格,分别由3个乘以4个(分别是宽度,高度)。 If the user rotates to landscape, I want to display them with a ViewPager of 3 by 2, and 3 by 2 in two pages. 如果用户旋转到横向,我想在两页中使用3×2和3×2的ViewPager显示它们。 So in the res/layout there's a grid of 12 items and in the res/layout-land there's a ViewPager, to which I need to give a PagerAdapter. 因此,在res / layout中有12个项目的网格,而在res / layout-land中有一个ViewPager,我需要给它一个PagerAdapter。

My question is: under the assumption I'm working with configChanges="orientation", how do I do that? 我的问题是:假设我正在使用configChanges =“ orientation”,我该怎么做? Or more specifically, Where for example do I give the ViewPager its PagerAdapter? 或更具体地说,例如,在何处给ViewPager提供PagerAdapter?

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if(display.getOrientation() == 0)
        setContentView(R.layout.main_portrait);
    else
        setContentView(R.layout.main_landscape); //getOrientation gives 1 here
}

You could make two layout files and at the beginning of your onCreate() (just after super.onCreate(bundle) line), put an if/else statement around this line: 您可以制作两个布局文件,并在onCreate()的开头(紧接在super.onCreate(bundle)行之后),在此行周围放置if / else语句:

setContentView(R.layout.main);

to look like this: 看起来像这样:

if(orientation==LANDSCAPE)
    setContentView(R.layout.main_landscape);
else
    setContentView(R.layout.main_portrait);

and from then on, wherever your java code would be different, just wrap it in the same condition. 从那时起,无论您的Java代码有何不同,只要将其包装在相同的条件下即可。 It's a little long-winded if your java code is very dependent on being in portrait, but I can't think of a better solution atm. 如果您的Java代码非常依赖于肖像,这有点麻烦,但是我想不到更好的atm解决方案。

Also, depending on your application and it's functionality, you may need to recreate the activity on orientation change. 另外,根据您的应用程序及其功能,您可能需要在方向更改时重新创建活动。 But again, it may not be necessary. 但是同样,它可能没有必要。

I hope this helps 我希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM