2013-01-11 114 views

回答

15

這裏是一個例子來幫助你:

your_button.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 

          Fragment frag = new YourFragment(Data yourdata); 


        FragmentTransaction ft = getFragmentManager().beginTransaction(); 
        ft.replace(R.id.fragment_container, frag); 
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); 
        ft.addToBackStack(null); 
        ft.commit(); 
       } 
    }); 

XML:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 


<FrameLayout android:name="fragments.YourInitialFragment" 
      android:id="@+id/fragment_container" 
      android:layout_weight="1" 
      android:layout_width="match_parent" 
      android:layout_height="0dip" /> 

</LinearLayout> 
+0

非常感謝朋友,這段代碼解決了我的大問題 –

0

Android documentation on this subject的讀:

所有片段到片段通信完成通過相關的活動。 兩個片段不應該直接通信。

事實上,如果您使用Android Studio模板添加片段,它將添加使用接口實現本文中描述的模式的模板代碼。

爲了滿足您的特定情況下,您的活動將實現這樣的接口:如對方均表示

public interface OnFragmentInteractionListener 
{ 
    void onButtonClick(Data data); 
} 

然後在該法的實施,該活動可以進行使用FragmentManager導航回答。文章給出了這個過程的更詳細的解釋。

相關問題