简体   繁体   中英

How to use the same basic layout with different contents in fragments?

I have a ViewPager with 3 different pages that all have their own fragment XML file. These fragments are basically the same for all 3 pages, they only differ in the content: Page 1 displays a RadioGroup, Page 2 shows a checkbox and Page 3 simply shows text.

On every page, there is a title and a description on the top and a button on the bottom. The content is displayed between the description and the button.

Currently I have copied the fragment file and just changed the content part. But this solution does not seem to be the best because I have to change 3 files when there is a layout change.

What is the recommended way to do this? Extend the LinearLayout class? Put all elements in one file and dynamically show/hide the elements I need? Any better suggestions?

One solution is you could have the page XML file and in the area your content differs, you could put an empty layout tag with an ID like layoutPlaceholder in that space, which is where you would programmatically insert the RadioGroup, the Checkbox, and Text XML layouts in your code.

The XML structure could look like this:

- Page.xml
   - Page_RadioGroup.xml
   - Page_checkbox.xml
   - Page_text.xml

This question explains how to inflate those sub-page xml files inside Page.xml

If you wanted to create the RadioGroup, Checkbox, and Text content programmatically instead of having 3 extra xml files, you could do that too, but I personally like to keep all my element layout in XML.

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