我添加使用XML的片段和它工作得很好,但是當我試圖將它添加動態它沒有在主要活動出現我的碎片也不會出現在主要活動
FragmentActivity.java:
package com.example.pc.learn_again;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.os.PersistableBundle;
public class FragmentActivity2 extends Activity{
@Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.mainfragment2);
//adding the fragment using Java code---dynamically ya3ni//
//create an object of the intended frag//
Fragment3 frag = new Fragment3();
//get the manager
FragmentManager manager = getFragmentManager();
//start the transaction
FragmentTransaction transaction = manager.beginTransaction();
//add to the layout
transaction.add(R.id.mylayout,frag,"fragment3");//--note: the parameters used are 1- the id of the main layout 2- the intended fragment 3- a key for future use//
//finish using the below
transaction.commit();
}
}
Fragment3.java:
package com.example.pc.learn_again;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment3 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment3,container,false);
}
}
的fragment3.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/highlighted_text_material_light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView3"
android:layout_gravity="center_horizontal"
android:layout_margin="40dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button12"
android:layout_below="@+id/textView3"
android:layout_margin="40dp"
android:layout_gravity="center_horizontal" />
</RelativeLayout>
的mainfragment2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mylayout">
</LinearLayout>
我檢查了所有以上和XML文件及其類別和所有是正確的之間的連接,雖然當我測試它的碎片不會在活動顯示
檢查了嗎? http://stackoverflow.com/questions/18296868/how-to-add-a-fragment-to-a-programmatically-generated-layout –
我看到的一些東西,沒有測試你的代碼: - 嘗試導入android.support.v4。*類爲您的FragmentManager,FragmentTransaction和片段 - 嘗試改變你的活動擴展FragmentActivity - 使用不同的onCreate()方法 - 一個沒有PersistentState –