I am trying to programmatically add a Fragment
to a ScrollView
that has a LinearLayout
. For some reason, when I call the following function, it doesn't appear to add any element to the LinearLayout
.
Here is the code: When the user clicks a button the following code is called that is supposed to add the fragment to the 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;
}
}
This function calls the following function for every class in the 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);
}
The Fragment itself is here:
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;
}
}
After some debugging, I have found that when the onCreateView() is called, it receivies a null value for container. I have modeled my code after the examples given here: How do I add a Fragment to an Activity with a programmatically created content view and here: http://developer.android.com/training/basics/fragments/fragment-ui.html
EDIT: Also if I use this same code but try adding a textview instead of a fragment it works just fine.