碎片与维护性Java代码之间的区别?

问题描述 投票:0回答:2

我正在android studio上制作一个BMI计算器应用程序,对于初学者来说,我只希望此代码起作用:

edit_height = (EditText) findViewById(R.id.edit_height);
        edit_weight = (EditText) findViewById(R.id.edit_weight);
        button_calculate_bmi = (Button) findViewById(R.id.button_calculate_bmi);
        text_results = (TextView) findViewById(R.id.text_results);

        button_calculate_bmi.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v){
                    String results = "Results:";
                 //   int height = Integer.parseInt(edit_height.getText().toString());
                   results += "hey I clicked a button!";
                   text_results.setText(results);
            }
        });

((我知道id不会计算,但我只希望它正常工作,之后我将继续执行代码)

问题是此代码是为ActivityMain编写的,但我的BMi计算器在另一个片段上。我该怎么做才能使这项工作?我可以在ActivityMain上编写代码然后链接吗?还是对代码进行更改并将其放在片段上?预先感谢。

我已经在代码开头声明了变量,如下所示:


    TextView text_results;
    EditText edit_height, edit_weight;
    Button button_calculate_bmi;  ```
java android android-studio android-fragments
2个回答
0
投票

您可以在另一个类中编写BMI计算器代码,然后可以在所需的任何位置(ActivityFragment)调用该函数

public class Utils {
    public static float BMICalculate(int weight, int height) {
        // calculate your result

        return result;
    }
}

以及您的活动:

button_calculate_bmi.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v){
            String results = "Results:";
            //   int height = Integer.parseInt(edit_height.getText().toString());

            results += Utils.BMICalculate(weight, height);
            text_results.setText(results);
    }
});

0
投票

您只需要添加片段并调用

val fragment = ExampleFragment()
// YOur fragment's container and fragment's name
fragmentTransaction.add(R.id.fragment_container, fragment)
fragmentTransaction.commit()

//您的主要活动需要一个FrameLayout

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>


</androidx.constraintlayout.widget.ConstraintLayout>

此链接允许您了解我在说什么

https://developer.android.com/guide/components/fragments

© www.soinside.com 2019 - 2024. All rights reserved.