将片段添加到活动

时间:2015-10-22 10:54:03

标签: java android android-fragments view fragment

我正在尝试将一些孩子添加到父LinearLayout。我搜索了一些,发现这些孩子需要成为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>

我的活动: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);
    }
}

当我在我的设备上运行时,应用程序崩溃并给我发错信息:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

0 个答案:

没有答案