简体   繁体   English

如何避免片段代码重复?

[英]How do I avoid code duplication for fragments?

If I want to create a tabbed activity with more than 10 swipable fragments, what other option do I have rather than to create 10 different Fragment classes with layouts and inflate they based on their position in the tabbed layout. 如果我要创建一个包含超过10个可滑动片段的选项卡式活动,我还有什么其他选择,而不是创建具有布局的10个不同的Fragment类并根据它们在选项卡式布局中的位置来填充它们。

That obviously sounds like a lot of duplicated code. 显然,这听起来像是很多重复的代码。

My question, fair and simple, is there any other way to avoid this? 我的问题,公平而简单,还有其他方法可以避免这种情况吗?

You can create one fragment class and then use the int value based on its position in the tabs to determine which layout to inflate in the onCreate method where you usually inflate a single layout view. 您可以创建一个片段类,然后根据其在选项卡中的位置使用int值来确定要在通常创建单个布局视图的onCreate方法中onCreate哪个布局。

Example

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(tabNumber == 1){
        setContentView(R.layout.fragment_layout1);
    }else if(tabNumber == 2){
        setContentView(R.layout.fragment_layout2);
    }else{
        setContentView(R.layout.fragment_layout3);
    }

}

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

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