0
我有一個由兩個按鈕和一個片段組成的視圖。如果按下按鈕1,則應該顯示一個片段(這是一個textview)。如果按下按鈕2,則會顯示片段2(這是一個textview)。問題是我只想要顯示一個片段。如果我按下按鈕的前後片段,則在片段1和片段2之間切換時總是顯示片段1。當我打算展示一個片段時顯示兩個片段
這是爲什麼?我怎樣才能解決這個問題,所以只顯示一個片段?
這裏是java類:
package com.example.fragmentstest;
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
public class MainActivity extends Activity {
@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 FragmentTwo();
}else {
fr = new FragmentOne();
}
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();
}
}
下面是XML類:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Fragment No.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 No.2" />
<fragment
android:name="com.example.fragmentstest.FragmentOne"
android:id="@+id/fragment_place"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>