简体   繁体   中英

How to get AlertDialog setPositiveButton to pull text from editText and place in listView

I am new to app development. On this layout I have a floating Action Button that opens AlertDialog when press.I am try to do is when user selects the setPositiveButton inside that AlertDialog that will pull what user placed in the EditText field and place that into the listView/RecyclerView of that page. I have my Java and custom dialog xml code below. What do I need to add to make this possible.

 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; } } } 

Is there any changes I need to do my 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); } } } 

This is what my RecyclerAdpter is pulling from now. What I want is it to pull from the editText field in my AlertDialog that is using my dialog_fab.xml file but the onClickListener is the setPositiveButton.

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

This is my dialog_fab.xml file

 <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> 

There's two interactions you can achieve here:

  1. When your dialog is open and the user presses positive button, if the edittext is empty, the dialog closes and does nothing, if the edittext has text, the dialog closes and updates the recyclerview.
  2. When your dialog is open, as long as the edittext is empty, the positive button is greyed out (disabled). The moment theres text, the positibe button is now enabled. pressing the positive button while its enabled closes the dialog and updates the recyclerview.

Since updating the RecyclerView is the common denominator here, I'll address it first.

Since all of this is happening inside your fragment, you dont need to pass around a listener. Just fire an onAddWorkout() method of your fragment class...

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);
    }

    ...


}

Next is number 1 of the two cases which is the easier option:

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;
    }

    ...

}

The 2nd part

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;
    }

    ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM