2012-08-03 137 views
0

我試圖以編程方式將Fragment添加到ScrollView,它具有LinearLayout。出於某種原因,當我調用以下函數時,它似乎沒有向LinearLayout添加任何元素。不能將片段添加到活動

下面是代碼: 當用戶點擊一個按鈕,下面的代碼被稱爲是應該的片段添加到的LinearLayout

這個函數調用下面的函數,每類ArrayList中:

private void addCourse(Course c) { 
    LinearLayout destination = (LinearLayout) findViewById(R.id.addListCourses); 
    FrameLayout fl = new FrameLayout(this); 
    CreateFragTests frag = new CreateFragTests(); 
    fl.setId(frag.getId()); 
    fl.setLayoutParams(new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT)); 
    FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.add(fl.getId(), frag).commit(); 
    destination.addView(fl); 
    //frag.setCourse(c); 
} 

片段本身是在這裏:

public class CreateFragTests extends Fragment { 

private static int uniqID = 0; 
private static String uniqPrefix = "courseList"; 
private Course course; 

public CreateFragTests() { 
    super(); 
    uniqID++; 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    //After some debugging, I have found that container is passed as null to this 
    //this function which may be part of the problem? 
    return inflater.inflate(R.layout.activity_create_frag_tests, container, true); 
} 

public void setCourse(Course c) { 
    this.course = c; 
    setCourseName(course.name); 
    setInstructorsName(course.instructorLastName+", "+course.instructorFirstName); 
} 

public String getUniqID() { 
    return uniqPrefix+"_"+uniqID; 
} 
} 

經過一些調試後,我發現當onCreateView()被調用時,它會收到容器的空值。我有我的模擬代碼在這裏給出的例子後:How do I add a Fragment to an Activity with a programmatically created content view這裏:http://developer.android.com/training/basics/fragments/fragment-ui.html

編輯:另外,如果我使用相同的代碼,但嘗試添加一個TextView,而不是隻是正常工作的一個片段。

回答

1

問題出在這裏fl.setId(frag.getId());。而不是傳遞frag.getId()作爲它的id,你應該傳入一個唯一的id。

有2種方法,你可以做,無論是在XML或類 定義ID例如

private static final int CONTAINER_ID = 123456;

並用它來設置的FrameLayout ID。

fl.setId(CONTAINER_ID);

或者更簡單的方法將是如下

private void addCourse(Course c) { 
    CreateFragTests frag = new CreateFragTests(); 
    FragmentTransaction ft = getFragmentManager().beginTransaction(); 
    ft.add(R.id.addListCourses, frag).commit(); 
    //frag.setCourse(c); 
}