猿问

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

我想将一些变量传递给主类,并根据用户在前面的接口中的输入进行一些计算。我尝试过使用 setter 和 getters,但最令人困惑的部分是如何使用这些变量进行计算,而无需在 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(){


    }

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


浮云间
浏览 128回答 2
2回答

largeQ

如果您不想立即开始目标活动以获取传递的值,请使用共享首选项:设定重量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");

幕布斯7119047

如果需要在两个活动之间传递一些数据,则应使用 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");    }}有关更多详细信息,请参阅官方文档 开始其他活动
随时随地看视频慕课网APP

相关分类

Java
我要回答