简体   繁体   中英

Android almost same code to fit different layout

(First of all I'm sorry for my poor english...)

As title, I do know that following layout(s) to match different screen:

res/layout/main_activity.xml  For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml For 10” tablets (720dp wide and bigger)

In my APP, I'm using ViewPagerAdapter to manage my contents.

I got 3 page flow for Phone device :

在此处输入图片说明

And of course, user can see only 1 page at same time.

Now, I would like to set a bit different layout for 7" tablet :

在此处输入图片说明

I would like to put WebView to left of layout, and make it isolated from ViewPagerAdapter, so that it will stay visible for all time.

And 2 other page will be put at right of layout, and make it act as ViewPager (can be slide left/right).

Both version of layout will use same code to manage, but as you can see, the page flow have a little different. So I must make few change to archive my target.

Is that possible ?

In order to implement your layout with the least possible effort, you probably want to use nested fragments: regardless of the device you are using, each ViewPager panel will be handled by a "smart" container Fragment.

Nested fragments description on "Android developers"

The container Fragment handles the logic of which fragments should be loaded when the view is created, by checking the id of the Fragments/Views present in the currently loaded layout and creating/attaching the Fragments as needed.

For instance on an Android Phone the layout for the first panel will probably contain only a R.id.title, and not a R.id.list identifier: the container fragment can detect this by checking if findViewById(R.id.list) is null and create only the title fragment (where on a tablet the result will not be null).

As you can see, since the correct layout file is loaded automatically by Android, you don't need to implement much logic :)

The only task that remains is changing the number of pages shown by the ViewPager depending on the geometry of your screen (phone/tablet) which you might do in your Activity's onCreate method.

Keep in mind that this last step might be tricky if the orientation of your app changes due to device rotation.

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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