2016-06-01 94 views
-3

我真的很抱歉這個愚蠢的問題,但我一直在閱讀各種東西,但似乎無法通過我厚厚的頭骨。我真的很絕望,所以請耐心等待。去一個片段的其他片段

所以我得到了一個充滿文字的片段,說fragment_chapter_1.xml。其中一個文本需要進一步的解釋,所以我想在文本(Copyright Act (Amendment) 1997)被點擊(它不是可點擊xml佈局)時,它會去fragment_explain_law.xml

fragment_explain_law.xml有一個TextView explainLaw,這將得到的setText(在ExplainLawFragment.java),以它自己在fragment_chapter_1.xml單擊文本的解釋。我使用這種方式,因爲如果其他文本被點擊,它將重複使用相同的fragment_explain_law.xml,但explainLaw將設置不同的解釋。

這是代碼。

  1. Chapter1Fragment.java,它會查看fragment_chapter_one.xmllaw1Copyright Act (Amendment) 1997的ID。

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
    rootView = inflater.inflate(R.layout.fragment_chapter_1, container, false); 
    
    law1 = (TextView) rootView.findViewById(R.id.law1); 
    law1.setOnClickListener(this); 
    
    // Inflate the layout for this fragment 
    return rootView; 
    } 
    
  2. 當得到點擊law1fragment_explain_law.xml將被顯示。爲此,我通過去ExplainLawFragment.java(我做對了嗎?)。

    @Override 
    public void onClick(View v) { 
    // when law1 till law11 clicked, go to ExplainLawFragment.java to view fragment_explain_law.xml 
    Fragment fragment = null; 
    String title = null; 
    
    switch (v.getId()) { 
        case R.id.law1: 
         // view explainLaw 
         fragment = new ExplainLawFragment(); 
         title = "Copyright Act (Amendment) 1997"; 
         break; 
    } 
    

    }

  3. ExplainLawFragment.java

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
            Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.fragment_explain_law, container, false); 
    explainLaw = (TextView) rootView.findViewById(R.id.explainLaw); 
    explainLaw.setText("blahblahblah"); 
    // Inflate the layout for this fragment 
    return rootView; 
    } 
    

結果:沒有發生。

logcat的,當我點擊law1V/SettingsInterface: from settings cache , name = sound_effects_enabled , value = 1

我有什麼錯?請幫忙。

回答

2

你可以這樣調用第二個片段....

@Override 
public void onClick(View v) { 
// when law1 till law11 clicked, go to ExplainLawFragment.java to view fragment_explain_law.xml 
Fragment fragment = null; 
String title = null; 

switch (v.getId()) { 
case R.id.law1: 
    // view explainLaw 
    fragment = new ExplainLawFragment(); 
    title = "Copyright Act (Amendment) 1997"; 
FragmentManager fragmentManager = getFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
fragmentTransaction.replace(R.id.container, fragment); 
fragmentTransaction.addToBackStack(null); 
fragmentTransaction.commit(); 
    break; 

}

希望這將幫助你..

+0

這個解決問題。非常感謝你! – August

+0

儘管標題沒有改變 – August

+0

你可以在第二個片段onCreateView()方法中設置標題,如.... getActivity()。setTitle(「Your title」); –