這些坑踩過好幾次了,必須總結以下,留待以後片段相關開發可以避免。
1.靜態片段,每個片段必須設置它的id或tag
在佈局中加一個靜態片段,必須設置id或者tag,無論是否有用到。否則在佈局被加載時會崩潰。因爲在重啓 Activity 時,系統需要使用該標識符來恢復片段
<fragment
android:id="@+id/frag"
.../>
或者:
<fragment
android:tag="tagName"
.../>
2.導入包不一致會導致加載時崩潰
(1)片段導入包:import android.app.Fragment;
此時,加載該片段的Activity的父類沒有什麼特殊要求,比如繼承自Activity。下面是一個例子:
片段:
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragTest extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
return view;
}
}
加載片段的Activity:
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
(2)片段導入包:import android.support.v4.app.Fragment;
此時加載片段的Activity就必須繼承自FragmentActivity或它的字類(注意:AppCompatActivity就是FragmentActivity的子類,而AppCompatActivity是新建activity的默認父類)
3.顯示加載片段的視圖(不是必須的,但建議去做)
要想在preview中將片段裏的佈局顯示出來需要加入下面兩句:
xmlns:tools="http://schemas.android.com/tools"
tools:layout="@layout/fragment_layout"
其中第一句一般寫在最外層的佈局屬性裏,第二句寫在要顯示的片段屬性裏,fragment_layout是片段的佈局文件。添加這兩句其實有快捷的方式:在沒有這兩句的前提下,Preview的下端會直接報錯,點擊一下 Use @layout/fragment_layout,就會在該添加的位置自動添加以上兩句。
4.動態加載片段remove失效,replace效果差
如果在活動的佈局文件中定義了FragmentLayout,其中又有fragment的話,例如像這樣:
<FrameLayout
android:id="@+id/frag_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<fragment
android:name="com.example.testall.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/frag_1"/>
</FrameLayout>
那麼,在java代碼中使用fragmentTransaction.remove()是無效的,可以選擇在java代碼裏用fragmentTransaction.add()添加片段,在佈局中將<fragment ...>
去掉,讓FragmentLayout在原位置,這樣remove()就有用了。
並且在上面例子的情況下,fragmentTransaction.replace()也無法真正的替換掉片段,新片段會在原片段上面,而可以通過設置新片段佈局的background掩蓋下面的原片段。