如何将变量从不同的类传递到主类

时间:2019-03-18 18:26:45

标签: java android

我想将一些变量传递给主类,并根据先前界面中的用户输入进行一些计算。我尝试使用setter和getter,但最令人困惑的部分是如何使用这些变量进行计算而不在TextView中显示它们。

public class Weight extends AppCompatActivity implements View.OnClickListener {

    public static AutoCompleteTextView userWeight;
    private Button secondPage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight);

        userWeight =(AutoCompleteTextView) findViewById(R.id.weight);
        secondPage = (Button) findViewById(R.id.toHeightPage);

        secondPage.setOnClickListener(this);

    }

    }

    private void enterWeight(){
        String weight = userWeight.getText().toString().trim();

        if(TextUtils.isEmpty(weight)){
            Toast.makeText(Weight.this,"Please Enter your weight", Toast.LENGTH_SHORT).show();

        return;
    }

在该类中,我想获取权重的值并在主类中使用它,这是主类代码。

public class Main_Interface extends AppCompatActivity {
    public TextView results;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main__interface);

        Toolbar toolbar = findViewById(R.id.toolbar1);
        setSupportActionBar(toolbar);

        results = (TextView)findViewById(R.id.results);

    }
    public void calculateBMR(){

    }

我将使用计算方法来使用应用程序中的所有变量来给我结果。

2 个答案:

答案 0 :(得分:0)

如果您需要在两个活动之间传递一些数据,则应为此使用Intent:

class ActivityA extends AppCompatActivity {
    ...

    void startActivityB(String code) {
        Intent i = new Intent(this, ActivityB.class);
        i.putExtra("code", code);
        startActivity(i);
    }
}


class ActivityB extends AppCompatActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ...
        String code = getIntent().getStringExtra("code");
    }
}

有关更多详细信息,请参见官方文档Start another activity

答案 1 :(得分:0)

如果您不想立即开始目标活动以获取传递的值,请使用 SharedPreferences

//设置体重

String weight = userWeight.getText().toString().trim();

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("PrefWeightKey", weight );
editor.apply();

//获得体重

SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String retrievedValue = sharedPreferences.getString("PrefWeightKey", "");

其他用途意图

//设置体重

Intent intent = new Intent(Weight.this, Main_Interface.class);
intent.putExtra("PrefWeightKey", weight);
startActivity(intent);

//获得体重

String retrievedValue = getIntent().getStringExtra("PrefWeightKey");
相关问题