为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

浮云间 2022-08-17 17:02:44
我想将一些变量传递给主类,并根据用户在前面的接口中的输入进行一些计算。我尝试过使用 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(){    }我将使用计算方法来使用应用程序中的所有变量来为我提供结果。
查看完整描述

2 回答

?
largeQ

TA贡献2039条经验 获得超8个赞

如果您不想立即开始目标活动以获取传递的值,请使用共享首选项:


设定重量


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");


查看完整回答
反对 回复 2022-08-17
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

如果需要在两个活动之间传递一些数据,则应使用 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");

    }

}

有关更多详细信息,请参阅官方文档 开始其他活动


查看完整回答
反对 回复 2022-08-17
  • 2 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号