2016-04-10 1 views
0

Я новичок в разработке приложений. На этом макете у меня есть плавающая кнопка действия, которая открывает AlertDialog при нажатии. Я пытаюсь сделать это, когда пользователь выбирает setPositiveButton внутри этого AlertDialog, который вытащит то, что пользователь разместил в поле EditText, и поместил его в listView/RecyclerView этой страницы , У меня есть мой Java и пользовательский код xml-кода ниже. Что мне нужно добавить, чтобы сделать это возможным.Как получить AlertDialog setPositiveButton вытащить текст из editText и поместить в listView

public class WorkoutFragment extends Fragment { 
 
    RecyclerView recyclerView; 
 

 

 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
 
     View rootView = inflater.inflate(R.layout.workout_layout, container, false); 
 
     recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); 
 
     setupRecyclerView(recyclerView); 
 

 
     FloatingActionButton button = (FloatingActionButton) rootView.findViewById(R.id.fab2); 
 
     button.setOnClickListener(new View.OnClickListener() { 
 
      @Override 
 
      public void onClick(View v) { 
 
       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
 
       // Get the layout inflater 
 
       LayoutInflater inflater = getActivity().getLayoutInflater(); 
 

 
       // Inflate and set the layout for the dialog 
 
       // Pass null as the parent view because its going in the dialog layout 
 
       builder.setView(inflater.inflate(R.layout.dialog_fab, null)) 
 
         // Add action buttons 
 
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
 
          @Override 
 
          public void onClick(DialogInterface dialog, int id) { 
 
          } 
 
         }) 
 
         .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
 
          public void onClick(DialogInterface dialog, int id) { 
 
           // User cancelled the dialog 
 
          } 
 
         }); 
 
       // Create the AlertDialog object and return it 
 
       AlertDialog dialog = builder.create(); 
 
       dialog.show(); 
 
      } 
 
     }); 
 
     return rootView; 
 
    } 
 

 

 
    private void setupRecyclerView(RecyclerView recyclerView) { 
 
     recyclerView.setLayoutManager(new LinearLayoutManager(recyclerView.getContext())); 
 
     recyclerView.setAdapter(new SimpleStringRecyclerViewAdapter(getActivity(), 
 
       VersionModel.data)); 
 
    } 
 

 
    public static class SimpleStringRecyclerViewAdapter extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> { 
 
     private String[] mValues; 
 
     private Context mContext; 
 

 
     public static class ViewHolder extends RecyclerView.ViewHolder { 
 

 
      public final View mView; 
 
      public final TextView mTextView; 
 

 
      public ViewHolder(View view) { 
 
       super(view); 
 
       mView = view; 
 
       mTextView = (TextView) view.findViewById(android.R.id.text1); 
 
      } 
 

 
     } 
 

 
     public String getValueAt(int position) { 
 
      return mValues[position]; 
 
     } 
 

 
     public SimpleStringRecyclerViewAdapter(Context context, String[] items) { 
 
      mContext = context; 
 
      mValues = items; 
 
     } 
 

 
     @Override 
 
     public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
 
      View view = LayoutInflater.from(parent.getContext()) 
 
        .inflate(android.R.layout.simple_list_item_1, parent, false); 
 
      return new ViewHolder(view); 
 
     } 
 

 
     @Override 
 
     public void onBindViewHolder(final ViewHolder holder, final int position) { 
 
      holder.mTextView.setText(mValues[position]); 
 
      holder.mView.setOnClickListener(new View.OnClickListener() { 
 
       @Override 
 
       public void onClick(View v) { 
 
        Snackbar.make(v, getValueAt(position), Snackbar.LENGTH_SHORT).show(); 
 
       } 
 
      }); 
 
     } 
 

 
     @Override 
 
     public int getItemCount() { 
 
      return mValues.length; 
 
     } 
 
    } 
 
}

Есть ли какие-либо изменения, я должен сделать мой RecyclerAdapter?

public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleRecyclerAdapter.VersionViewHolder> { 
 
    List<String> versionModels; 
 
    Context context; 
 

 
    public SimpleRecyclerAdapter(Context context){ 
 
     this.context = context; 
 
    } 
 

 
    public SimpleRecyclerAdapter(List<String> versionModels){ 
 
     this.versionModels = versionModels; 
 
    } 
 

 
    @Override 
 
    public VersionViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
 
     View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.workout_layout, parent, false); 
 
     VersionViewHolder viewHolder = new VersionViewHolder(view); 
 
     return viewHolder; 
 
    } 
 

 
    @Override 
 
    public void onBindViewHolder(SimpleRecyclerAdapter.VersionViewHolder holder, int position) { 
 
     holder.title.setText(versionModels.get(position)); 
 
    } 
 

 
    @Override 
 
    public int getItemCount() { 
 
     return versionModels == null ? 0 : versionModels.size(); 
 
    } 
 

 
    class VersionViewHolder extends RecyclerView.ViewHolder{ 
 
     CardView cardItemLayout; 
 
     TextView title; 
 

 
     public VersionViewHolder(View itemView){ 
 
      super(itemView); 
 
      cardItemLayout = (CardView)itemView.findViewById(R.id.cardlist_item); 
 
      title = (TextView)itemView.findViewById(R.id.listitem_name); 
 
     } 
 

 
    } 
 
}

Это то, что мой RecyclerAdpter тянет теперь. Я хочу, чтобы вытащить из поля editText в моем AlertDialog, который использует файл dialog_fab.xml, но onClickListener - это setPositiveButton.

public class VersionModel { 
 
    public static final String[] data = { 
 
      "cupcake", "donut", "eclair", "froyo", "gingerbread", 
 
      "honeycomb", "ice cream sandwich", "jelly bean", "kit kat", 
 
      "Lollipop", "marshmallow" 
 
    }; 
 

 
}

Это мой файл dialog_fab.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
 
    android:orientation="vertical" 
 
    android:layout_width="wrap_content" 
 
    android:layout_height="wrap_content"> 
 
    <TextView 
 
     android:layout_width="match_parent" 
 
     android:layout_height="64dp" 
 
     android:scaleType="center" 
 
     android:background="#F44336" 
 
     android:text="Test Title" 
 
     android:textSize="55sp" 
 
     android:contentDescription="@string/app_name" /> 
 
    <EditText 
 
     android:id="@+id/workoutTitle" 
 
     android:inputType="text" 
 
     android:layout_width="match_parent" 
 
     android:layout_height="wrap_content" 
 
     android:layout_marginTop="16dp" 
 
     android:layout_marginLeft="4dp" 
 
     android:layout_marginRight="4dp" 
 
     android:layout_marginBottom="4dp" 
 
     android:hint="Name" /> 
 

 

 
</LinearLayout>

+0

Я не вижу «ListView» или «Adapter» в ваш код. –

+0

@MikeM. У меня есть дополнительная информация. Надеюсь, это предоставит вам необходимую информацию, чтобы помочь мне. Я пытаюсь найти этот ответ в течение 2 недель. – hilllomax

ответ

0

Там две взаимодействия можно достичь здесь:

  1. Когда ваш диалог открыт, и пользователь нажимает положительную кнопку, если edittext пуст, диалог закрывается и ничего не делает, если текст edittext имеет текст, диалог закрывается и обновляет recyclerview.
  2. Когда ваше диалоговое окно открыто, до тех пор, пока edittext пуст, положительная кнопка недоступна (отключена). В тот момент, когда текст текста, кнопка positibe теперь включена. нажатие положительной кнопки, когда оно включено, закрывает диалог и обновляет recyclerview.

Поскольку обновление RecyclerView является общим знаменателем здесь, я обращусь к нему первым.

Поскольку все это происходит внутри вашего фрагмента, вам не нужно проходить вокруг слушателя. Просто сгореть onAddWorkout() метод вашего класса фрагмента ...

public class WorkoutFragment extends Fragment { 
    RecyclerView recyclerView; 

    public View onCreateView(...) { 
     ... 
    } 

    ... 

    private void onAddWorkout(String workoutTitle) { 
     SimpleStringRecyclerViewAdapter adapter = (SimpleStringRecyclerViewAdapter) recyclerView.getAdapter; 

     // You should probably use an ArrayList so that addition and removal of items will not require creating another object 
     int length = adapter.mValues.length; 
     adapter.mValues = Arrays.copyOfRange(adapter.mValues, 0, length + 1); 
     adapter.mValues[length] = workoutTitle; 
     adapter.notifyItemInserted(length); 
    } 

    ... 


} 

Следующая является номер 1 из двух случаев которых является более простой вариант:

public class WorkoutFragment extends Fragment { 
    RecyclerView recyclerView; 


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.workout_layout, container, false); 
     recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); 
     setupRecyclerView(recyclerView); 

     FloatingActionButton button = (FloatingActionButton) rootView.findViewById(R.id.fab2); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
       // Get the layout inflater 
       LayoutInflater inflater = getActivity().getLayoutInflater(); 

       View v = inflater.inflate(R.layout.dialog_fab, null); 
       EditText e = view.findViewById(R.id.workoutTitle); 
       builder.setView(v) 
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
          @Override 
          public void onClick(DialogInterface dialog, int id) { 
           if (!TextUtils.isEmpty(e.getText().toString())) { 
            // This block is responsible for checking if edittext is empty and carrying out the action 
            onAddWorkout(e.getText().toString()); 
           } 
          } 
         }) 
         .setNegativeButton("Cancel", ...); 
       // Create the AlertDialog object and return it 
       AlertDialog dialog = builder.create(); 
       dialog.show(); 
      } 
     }); 
     return rootView; 
    } 

    ... 

} 

вторая часть

public class WorkoutFragment extends Fragment { 
    RecyclerView recyclerView; 


    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.workout_layout, container, false); 
     recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView); 
     setupRecyclerView(recyclerView); 

     FloatingActionButton button = (FloatingActionButton) rootView.findViewById(R.id.fab2); 
     button.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); 
       // Get the layout inflater 
       LayoutInflater inflater = getActivity().getLayoutInflater(); 

       View v = inflater.inflate(R.layout.dialog_fab, null); 
       EditText e = view.findViewById(R.id.workoutTitle); 
       builder.setView(v) 
         .setPositiveButton("Yes", ...) // You can set your normal listener here. 
         .setNegativeButton("Cancel", ...); 
       // Create the AlertDialog object and return it 
       AlertDialog dialog = builder.create(); 
       dialog.show(); 

       // !mportant - this should be called **after** dialog.show() or in a dialog OnShowListener 
       // This is because the buttons arent truly attached till the dialog is shown; 

       final Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE); 

       e.addTExtWatcher(new TextWatcher() { 
        ... 

        public void onTextChanged(CharSequence s, int start, int before, int count) { 

         positiveButton.setEnabled(s.length() > 0); 
        }      

        ... 
       }); 
      } 
     }); 
     return rootView; 
    } 

    ... 

} 
Смежные вопросы