2014-09-23 61 views

回答

0

XML

<Button 
    android:id="@+id/button1" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Fragment 1" 
    android:onClick="selectFrag" /> 

<Button 
    android:id="@+id/button2" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:onClick="selectFrag" 
    android:text="Fragment 2" /> 

<fragment 
    android:name="xxxxxxxxxx.Fragment1" 
    android:id="@+id/fragment_place" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" /> 

活動

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

    setContentView(R.layout.activity_main); 
} 

public void selectFrag(View view) { 
    Fragment fr; 

    if(view == findViewById(R.id.button2)) { 
     fr = new Fragment2(); 

    }else { 
     fr = new Fragment1(); 
    } 

    FragmentManager fm = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fm.beginTransaction(); 
    fragmentTransaction.replace(R.id.fragment_place, fr); 
    fragmentTransaction.commit(); 

} 
相關問題