Ящик навигации - Активность к фрагменту - PullRequest
0 голосов
/ 31 января 2020

Я новичок в Android Studio и у меня есть несколько вопросов. Чтобы начать знакомство, я создал простую калькуляторную программу с флажками и переключателями. Хотя я пошел дальше, чтобы выполнить основное задание, позвоните в чекбокс калькулятор и в радио калькулятор, чем я доволен. Тем не менее, я хочу еще go и попробую использовать Навигационный ящик для двух калькуляторов. После некоторой настройки и тестирования мне удалось понять, что делает то, что работает. Позже я наткнулся на фрагменты, которые, как я понимаю, немного отличаются от деятельности. Я читал, что нужно внедрять onclick программно, когда речь идет о таких случаях, как rad ios и тому подобное. Я хотел бы знать, как преобразовать следующий код во что-то, что может обработать фрагмент.

    public class radio extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_radio);
    }
    public void onRadioButtonClicked(final View view) {
        final boolean checked = ((RadioButton) view).isChecked();

        Button button = (Button) findViewById(R.id.calBtn);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText num1editTxt = (EditText) findViewById(R.id.num1editTxt);
                EditText num2editTxt = (EditText) findViewById(R.id.num2editTxt);
                TextView resultViewTxt = (TextView) findViewById(R.id.resultViewTxt);

                if (TextUtils.isEmpty(num1editTxt.getText().toString()) || TextUtils.isEmpty(num2editTxt.getText().toString())){
                    Toast.makeText(radio.this, "Empty field not allowed!", Toast.LENGTH_LONG).show();
                }
                else {
                    int num1 = Integer.parseInt(num1editTxt.getText().toString());
                    int num2 = Integer.parseInt(num2editTxt.getText().toString());
                    int result = 0;
                    switch (view.getId()) {
                        case R.id.addRadio:
                            if (checked) {
                                result = num1 + num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.subRadio:
                            if (checked) {
                                result = num1 - num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.multiRadio:
                            if (checked) {
                                result = num1 * num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.divRadio:
                            if (checked) {
                                result = num1 / num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                    }
                }
            }
        });
    }
    }

Вот xml фрагмента с пользовательским интерфейсом, скопированным из действия без изменений:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/num1editTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="104dp"
        android:ems="10"
        android:hint="@string/hint"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/num2editTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="44dp"
        android:ems="10"
        android:hint="@string/hint"
        android:importantForAutofill="no"
        android:inputType="number"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/num1editTxt" />

    <RadioGroup
        android:id="@+id/radiGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/calBtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/num2editTxt">

        <RadioButton
            android:id="@+id/addRadio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="@{() -> fragment.buttonClicked()}"
            android:text="@string/add"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <RadioButton
            android:id="@+id/subRadio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked"
            android:text="@string/sub" />

        <RadioButton
            android:id="@+id/multiRadio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked"
            android:text="@string/multi" />

        <RadioButton
            android:id="@+id/divRadio"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onRadioButtonClicked"
            android:text="@string/div" />

    </RadioGroup>

    <Button
        android:id="@+id/calBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="236dp"
        android:text="@string/button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.501"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/num2editTxt" />

    <TextView
        android:id="@+id/resultViewTxt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/result"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/calBtn"
        app:layout_constraintVertical_bias="0.245" />

    </androidx.constraintlayout.widget.ConstraintLayout>

А вот моя ужасная неудачная попытка фрагмента кода:

    public class GalleryFragment extends Fragment implements View.OnClickListener {

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        final View root = inflater.inflate(R.layout.fragment_gallery, container, false);

        root.findViewById(R.id.addRadio).setOnClickListener(this);
        root.findViewById(R.id.subRadio).setOnClickListener(this);
        root.findViewById(R.id.multiRadio).setOnClickListener(this);
        root.findViewById(R.id.divRadio).setOnClickListener(this);


        return root;
    }
    @Override
    public void onClick(final View view) {
        final boolean checked = ((RadioButton) view).isChecked();

        View vi;
        Button button = view.findViewById(R.id.calBtn);
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText num1editTxt = v.findViewById(R.id.num1editTxt);
                EditText num2editTxt = v.findViewById(R.id.num2editTxt);
                TextView resultViewTxt = v.findViewById(R.id.resultViewTxt);

                if (TextUtils.isEmpty(num1editTxt.getText().toString()) || TextUtils.isEmpty(num2editTxt.getText().toString())){
                    Toast.makeText(getActivity(), "Empty field not allowed!", Toast.LENGTH_LONG).show();
                }
                else {
                    int num1 = Integer.parseInt(num1editTxt.getText().toString());
                    int num2 = Integer.parseInt(num2editTxt.getText().toString());
                    int result = 0;
                    switch (view.getId()) {
                        case R.id.addRadio:
                            if (checked) {
                                result = num1 + num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.subRadio:
                            if (checked) {
                                result = num1 - num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.multiRadio:
                            if (checked) {
                                result = num1 * num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                        case R.id.divRadio:
                            if (checked) {
                                result = num1 / num2;
                                resultViewTxt.setText(result + "");
                            }
                            break;
                    }
                }
            }
        });
    }
    }
...