如何正确地以编程方式将EditText添加到Fragment?

时间:2014-06-28 08:05:25

标签: java android eclipse android-edittext

这是我的 Java 代码:

View RV2 = inflater.inflate(R.layout.fragment__dummy,container, false);
LinearLayout LL = (LinearLayout) RV2 .findViewById(R.id.section_label);
EditText ET = new EditText(getActiity());
ET.setText("LOL");
ET.setId(5);
ET.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
LL.addView(ET);
return RV;

因此,当我跑步时,红色行未亮起应用程序停止

谢谢!

3 个答案:

答案 0 :(得分:1)

您正在RV2中填充布局并返回RV

更改

return RV;

return RV2;

您必须返回正在给布局充气的View

答案 1 :(得分:0)

View RV2 = inflater.inflate(R.layout.fragment__dummy,container, false);
LinearLayout LL = (LinearLayout) RV2 .findViewById(R.id.section_label);
EditText ET = new EditText(getActiity());
ET.setText("LOL");
ET.setId(5);
ET.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
LL.addView(ET);

((ViewGroup)RV2).addView(LL);

return RV2;

请试一试。

答案 2 :(得分:0)

尝试这种方式它将起作用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true"
        >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/family_detail_linear"
        android:orientation="vertical"
        ></LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/family_detail_addbutton"
        android:text="Add More"
        />

</LinearLayout>
    </ScrollView>

</LinearLayout>

Java代码

public class MyFrag extends Fragment{


    private Button addmoremember;
    private Activity activity;
    private LinearLayout layout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.family_details, container, false);

        activity=getActivity();
        addmoremember=(Button)rootView.findViewById(R.id.family_detail_addbutton);
        layout=(LinearLayout)rootView.findViewById(R.id.family_detail_linear);
       addmoremember.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText edttexname= new EditText(activity);
                edttexname.setHint("Enter Name");

                layout.addView(edttexname);

            }
        });

        return rootView;
    }
}