Диалог оповещений с EditText и положительной отрицательной кнопкой - PullRequest
0 голосов
/ 08 февраля 2020

Я пытаюсь создать DialogFragment как

    public class PlaceFragment extends DialogFragment {
      public PlaceFragment() {
      }

      public static PlaceFragment newInstance() {
        PlaceFragment placeFragment = new PlaceFragment();
        Bundle args = new Bundle();
        args.putDouble("Latitude", 12.3456);
        placeFragment.setArguments(args);
        return placeFragment;
      }
     @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
      View v = inflater.inflate(R.layout.fragment_place, container, false);
    AlertDialog.Builder placePicker = new AlertDialog.Builder(getContext());
    placePicker.setView(R.layout.fragment_place)
        .setTitle("Enter Latitude and Longitude")
        .setPositiveButton("Ok", null);
//    return inflater.inflate(R.layout.fragment_place, container);
    return v;
  }
    }

, который должен называться:

case R.id.action_geolocate:
        FragmentManager fm = getSupportFragmentManager();
        PlaceFragment placeFragment = PlaceFragment.newInstance();
        placeFragment.show(fm, "");
        return true;

Но, как вы можете видеть, это не работает, так как это очевидно показывает только макет, который надут. Но я пытаюсь получить диалог с двумя строками EditText с кнопкой Ok и Dissmiss.

Если я использую полностью ручной способ, то я получаю editText, но не имею никакого представления, как получить это значение с OkButton, например:

 @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_place, container);
  }

Ответы [ 3 ]

0 голосов
/ 08 февраля 2020

Я думаю, вы должны реализовать

@Override public Dialog onCreateDialog(Bundle savedInstanceState) {

вместо

@Override public View onCreateView(Bundle savedInstanceState) {

и вернуть диалог вместо представления, и я думаю, было бы лучше, если бы вы не оставляли строку тега в .show(ft,"") пустой

0 голосов
/ 08 февраля 2020

если я правильно понимаю, что-то вроде этого должно работать:

 public class DialogEnterExit extends DialogFragment {

        public interface EnterExitDialogListener {
            void onFinishEditDialog(String event, String place, Location location);
        }

        EnterExitDialogListener mListener;

        private static final String TAG = DialogEnterExit.class.getSimpleName();

        AppCompatDialog mDialog;
        String mPlace;
        Location mLocation;



        public static DialogEnterExit newInstance(String place, Location location) {
            DialogEnterExit f = new DialogEnterExit();

            // Supply num input as an argument.
            Bundle args = new Bundle();
            args.putString("PLACE", place);
            args.putParcelable("LOCATION", location);
            f.setArguments(args);

            return f;
        }


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            mPlace = getArguments().getString("PLACE");
            mLocation = getArguments().getParcelable("LOCATION");
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            LayoutInflater layoutInflater = getActivity().getLayoutInflater();
            View view = layoutInflater.inflate(R.layout.layout_enter_exit_dialog,null);

            final RadioButton enter = view.findViewById(R.id.radio_enter);
            final RadioButton exit = view.findViewById(R.id.radio_exit);
            TextView place = view.findViewById(R.id.place_picked);

            place.setText(mPlace);

            enter.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (mListener != null) {

     mListener.onFinishEditDialog(getString(R.string.dialog_transition_entered), mPlace, 
      mLocation);
                    }
                    mDialog.dismiss();
                }
            });

            exit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    if (mListener != null) {

     mListener.onFinishEditDialog(getString(R.string.dialog_transition_exited), mPlace, 
   mLocation);
                    }

                    mDialog.dismiss();
                }
            });


            builder
                    .setView(view)
                    .setTitle(getString(R.string.dialog_title_event))
                    .setCancelable(true);

            mDialog = builder.create();
            return mDialog;
        }


        @Override
        public void onAttach(@NonNull Context context) {
            super.onAttach(context);

            // Verify that the host activity implements the callback interface
            try {
                // Instantiate the EditNameDialogListener so we can send events to the 
           host
                mListener = (EnterExitDialogListener) context;
            } catch (ClassCastException e) {
                // The activity doesn't implement the interface, throw exception
                throw new ClassCastException(context.toString()
                        + " must implement EnterExitDialogListener"  );
            }


        }

        @Override
        public void onDetach() {
            super.onDetach();

            mListener = null;
        }
    }

и представление в xml

   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="place:"
                android:layout_weight="1"/>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/place_picked"
                android:hint="place name"
                android:layout_weight="3"/>
        </LinearLayout>

        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radio_enter"
            android:text="@string/geofence_transition_entered"/>

        <RadioButton
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/radio_exit"
            android:text="@string/geofence_transition_exited"/>
        </LinearLayout>
    </LinearLayout>

и использовать:

 android.location.Location loc = new android.location.Location("");
    loc.setLatitude(location.getLatitude());
    loc.setLongitude(location.getLongitude());

  DialogEnterExit dialogEnterExit = DialogEnterExit.newInstance(location.getName(), loc);

    getSupportFragmentManager().beginTransaction()
            .add(dialogEnterExit, "enter exit dialog").commitAllowingStateLoss();
0 голосов
/ 08 февраля 2020

Вы можете

  • Создать расширение класса DialogFragment
  • переопределить и реализовать onCreateDialog для настройки внешнего вида диалогового окна. Здесь, создайте Dialog / AlertDialog, также можно заполнить его макет здесь.
  • В некоторых случаях вы хотите реализовать onCreateView и обрабатывать представления / действия там.

Надеюсь, это поможет .

...