我試圖以編程方式將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,而不是隻是正常工作的一個片段。