2016-04-13 3 views
2

Я создания следующего AlerDialog:Как получить EditText из фрагмента

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 вид из моего макета в коде? Поскольку я хочу иметь введенный текст после нажатия пользователем кнопки «ОК».

ответ

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); 
+0

Великий, он работает для меня. Большое спасибо – neustart47

1
AlertDialog.Builder alert = new AlertDialog.Builder(appContext); 
// inflate your view 
View inflatedView = LayoutInflator.from(appContext).inflate(R.layout.add_subcontractor_form) 
// find the edittext 
final EditText input = (EditText) inflatedView.findViewById(R.id. et_sub_name) 

alert.setTitle("Add subcontractors") 
    .setView(inflatedView); 

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(); 
Смежные вопросы