我正在尝试以编程方式将 a 添加Fragment
到ScrollView
具有LinearLayout
. 出于某种原因,当我调用以下函数时,它似乎没有向LinearLayout
.
这是代码:当用户单击按钮时,会调用以下代码,该代码应该将片段添加到 LinearLayout
public void refresh(View v) {
CourseManagement cm = CourseManagement.getInstance();
ArrayList<Course> courses = cm.getCourses();
if(courses.size()>0) {
Iterator<Course> it = courses.iterator();
while(it.hasNext()) {
Course c = it.next();
addCourse(c);
}
} else {
//No Classes In List;
}
}
此函数为 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() 时,它会收到容器的空值。我在此处给出的示例之后对我的代码进行了建模:如何使用以编程方式创建的内容视图将片段添加到 Activity和此处:http: //developer.android.com/training/basics/fragments/fragment-ui.html
编辑:另外,如果我使用相同的代码,但尝试添加一个文本视图而不是一个片段,它就可以正常工作。