如何从片段中获取EditText

时间:2016-04-13 16:24:57

标签: android android-fragments

我创建了下一个AlerDialog:

AlertDialog.Builder alert = new AlertDialog.Builder(appContext);

                alert.setTitle("Add subcontractors").setView(R.layout.add_subcontractor_form);

                //final EditText input = new EditText(appContext);

                alert.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String YouEditTextValue = input.getText().toString();
                    }
                });

                alert.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        // what ever you want to do with No option.
                    }
                });

                alert.show();

并有下一个布局:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
           <EditText
            android:layout_margin="10dp"
            android:id="@+id/et_sub_name"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:hint="Type name here"
            android:textSize="20sp"/>
</LinearLayout>

我的问题是,如何从代码中的布局中获取EditText视图? 因为我想在用户按下&#34; OK&#34;之后输入一个文本。按钮。

1 个答案:

答案 0 :(得分:3)

尝试这样做:

LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.add_subcontractor_form, null);
alert.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.et_sub_name);