2014-02-27 16 views
2

我使用的片段主详细架构
所有片段类具有相同的逻辑
是否有可能从布局到“分离”的片段,并使用只是一个片段类
所以这个代码:使用单个片段进行多个UI任务?

FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction(); 

     if("001".equalsIgnoreCase(id)){ 
        arguments.putString(Fragment001.ARG_ITEM_ID, id); 
        Fragment001 fragment = new Fragment001(); 
        fragment.setArguments(arguments);      fragManager.replace(R.id.item_detail_container, fragment); 
     } 
     else if("002".equalsIgnoreCase(id)){ 
        arguments.putString(Fragment002.ARG_ITEM_ID, id); 
        Fragment002 fragment = new Fragment002(); 
        fragment.setArguments(arguments); 
        fragManager.replace(R.id.item_detail_container, fragment); 
     } 

     fragManager.commit(); 

会变成喜欢的东西:

FragmentTransaction fragManager = getSupportFragmentManager().beginTransaction();    
        GenericFragment fragment = new GenericFragment();      
        fragment.setUiId(id) 
        fragManager.replace(R.id.item_detail_container, fragment); 
fragManager.commit(); 
  1. 列表项
+2

“的所有片段类具有相同的逻辑” - 意思'Fragment001'具有相同的源代码'Fragment002'? – TactMayers

+0

有10个片段8个是相同的(多个是否问题形式) – user648026

回答

3

是其可能的,你可以检查并选择onCreateView使用哪些布局?

public static final String ARG_ITEM_ID1 = "fragment001"; 

public static final String ARG_ITEM_ID2 = "fragment002"; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View rootView = null; 
    String id = "fragment001"; 
    if(ARG_ITEM_ID1.equalsIgnoreCase(id)){ 

     rootView = inflater.inflate(R.layout.fragment_1_layout, container, false); 
    } 
    else { 

     rootView = inflater.inflate(R.layout.fragment_2_layout, container, false); 
    } 
    return rootView; 
}