Как получить значения из DialogFragment? - PullRequest
0 голосов
/ 27 мая 2020

Я не могу понять, как использовать значения в моем методе onClick. У меня есть этот класс с методом onCreateDialog, который предлагает пользователю ввести следующее Пользователь получает запрос

Вот код

public class InfoPrompt extends AppCompatDialogFragment {
private EditText editTextTitle;
private EditText editTextAuthor;
private EditText editTextPageCount;
private EditText editTextDeadline;
//private InfoPromptListener listener;


@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();

    View view = inflater.inflate(R.layout.info_prompt, null);

    builder.setView(view);
    builder.setTitle("Add Work");
    builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            String bookTitle = editTextTitle.getText().toString();
            String bookAuthor = editTextAuthor.getText().toString();

            String pageCount = editTextPageCount.getText().toString();
            Long pageCountLong = Long.parseLong(pageCount);

            String deadline = editTextDeadline.getText().toString();
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date deadlineDate = null;
            try {
                deadlineDate = sdf.parse(deadline);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            Date currentDate = Calendar.getInstance().getTime();
            Long daysBetweenDates = currentDate.getTime() - deadlineDate.getTime();
            Long pagesPerDay = pageCountLong / daysBetweenDates;
            //listener.applyTexts(bookTitle,bookAuthor,pageCountLong,deadline,daysBetweenDates,pagesPerDay);



        }

    });
    editTextTitle = view.findViewById(R.id.bookTitle);
    editTextAuthor = view.findViewById(R.id.bookAuthor);
    editTextPageCount = view.findViewById(R.id.pageCount);
    editTextDeadline = view.findViewById(R.id.deadline);

    return builder.create();
}

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

Мне нужно использовать их в другом классе при надувании другого макета этими значениями.

I думал что-то в этом роде

private void applyTexts(String bookTitle, String bookAuthor, Long pageCountLong, String deadline, Long daysBetweenDates, Long pagesPerDay) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View view = inflater.inflate(R.layout.fragment_add_work, null, false);

    TextView bookTitleTV = view.findViewById(R.id.bookTitle);
    TextView bookAuthorTV = view.findViewById(R.id.bookAuthor);
    BubbleSeekBar seekBarBSB = view.findViewById(R.id.seekBar);
    TextView deadlineTV = view.findViewById(R.id.deadline);
    TextView pagesLeftTV = view.findViewById(R.id.pagesLeft);
    TextView todayReadTV = view.findViewById(R.id.todayRead);

    bookTitleTV.setText(bookTitle);
    bookAuthorTV.setText(bookAuthor);
    seekBarBSB.setProgress(pageCountLong);
    deadlineTV.setText(deadline);

    int getProgress = seekBarBSB.getProgress();
    Long pagesLeftLong = pageCountLong-getProgress;
    String pagesLeftString = Long.toString(pagesLeftLong);
    pagesLeftTV.setText(pagesLeftString);

    String ppd = Long.toString(pagesLeftLong/daysBetweenDates);
    todayReadTV.setText(ppd);

    thisLayout.addView(view);

. У меня небольшой опыт разработки android, поэтому многие вещи могут не иметь смысла, но вся помощь приветствуется

1 Ответ

0 голосов
/ 27 мая 2020

Для получения информации из EditText:

String userInput = editText.getText().toString().trim()
if (!userInput.isEmpty()) {
    anotherFunctionThatNeedsThisInfo(userInput);
}
private void anotherFunctionThatNeedsThisInfo(String userInput) {
    //Do what you need with the data
    String welcomeText = "Hello, your input is: " + userInput;
}

Вам нужно получить каждый EditText ввод отдельно.

Мы используем trim() для удаления пустых пробелов, которые пользователи могли случайно добавить к вводу.

Проверить, не является ли ввод пользователя пустым внутри оператора if. !isEpmty() проверяет, что он не пустой.

EditText никогда не возвращает null, он возвращает пустой, только если пользовательский ввод не добавлен.

...