I'm trying to add some children to a parent LinearLayout
. I searched some and found that these children need to be a Fragment
.
My fragment: faq_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/question_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:text="Title 1"/>
<TextView
android:id="@+id/answer_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textAlignment="center"
android:text="Description 1"
android:layout_marginTop="5dp"/>
</LinearLayout>
My Activity: new_activity.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:padding="20dp"
android:background="#0088ff"
android:onClick="test">
<LinearLayout
android:id="@+id/fragment_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
NewActivity.java:
public class NewActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.new_activity);
Map<String, String> info = new HashMap<>();
for (int i = 0; i < 5; i++) info.put("Question " + i, "Answer " + i);
for (Map.Entry<String, String> entry : info.entrySet()) {
FAQFragment faq = new FAQFragment();
// faq.titleLabel.setText(entry.getKey());
// faq.descriptionLabel.setText(entry.getValue());
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(R.id.fragment_view, faq);
ft.commit();
}
}
}
class FAQFragment extends Fragment {
// TextView titleLabel, descriptionLabel;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// titleLabel = (TextView)container.findViewById(R.id.question_text);
// descriptionLabel = (TextView)container.findViewById(R.id.answer_text);
return inflater.inflate(R.layout.faq_fragment, container);
}
}
When I run it on my device the app crashes and gices me error message:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.