2014-04-24 62 views
0

我有2個問題。首先,我可以說一個人,爲什麼這不起作用?我只是試圖改變片段,但他什麼都不做。我只看到第一個片段。更改分段動態

mainActivity:

... 
if (savedInstanceState == null) { 
     fm.beginTransaction() 
       .add(R.id.firstFragment, new firstFragment()).commit(); 
    } 

    findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      switchFragment(R.id.firstFragment, new firstFragment()); 
     } 
    }); 

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      switchFragment(R.id.secondFragment, new secondFragment()); 
     } 
    }); 

} 

private void switchFragment(int fragId, Fragment frag){ 
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
    ft.replace(fragId, frag); 
    ft.commit(); 
} 

片段像這樣在main.xml中:

<Fragment 
    android:id="@+id/firstFragment" 
    android:name="com.example.firstFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_above="@+id/View01" 
    android:layout_below="@+id/view1" /> 

Fragmentclass只有這個:

@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View view = inflater.inflate(R.layout.fragment_clublist, container, false); 

    return view; 
    } 

以及分段只是看起來像這樣:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Fragment1" 
    android:textAppearance="?android:attr/textAppearanceLarge" 
    android:textColor="#FFFF0000"/> 

我不知道,他爲什麼不改變片段。一個檢查,那switchFragment真的調用是真的。

第二個問題是:這是改變碎片的好方法嗎?什麼,如果我有10個片段?

感謝您的幫助! :)

回答

1
int fragId 

應該是容器的承載Fragment,不片段本身

的ID與id