java - How to pass variable from different class to the main class
问题描述
I want to pass some variables to the main class and do some calculations depend on the user input in the previous interfaces. I've tried to use setters and the getters but the most confusing part is how to use those variable to do the calculation without displaying them in 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;
}
in this class I want to get the value of the weight and use it in the main class, and here is the main class code.
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(){
}
I am going to use the calculation method to use all of the variables in the app to give me the results.
解决方案
如果您需要在两个活动之间传递一些数据,您应该为此使用 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");
}
}
有关更多详细信息,请查看官方文档开始另一个活动
推荐阅读
- r - R:在数据面板中绘制最后 N 个观察值,每天从网站更新
- c++ - 带有函数 ptr 的 BST,如何添加额外的参数?
- javascript - 使用 ReactJs 使用 UseContext 时遇到问题,我需要更改一个组件中的状态变量,并希望在另一个组件中更新状态
- compiler-construction - 为什么每个状态在`LR`解析表中最多出现一个`GOTO`列?
- python - 无法在 python 中安装包,readline (setup.py) 的错误构建轮
- python - 使用 Tensorflow 的 Dataset API 加载示例时出现类型错误
- python - 从 RGB 颜色列表在 python 中创建颜色映射
- three.js - 如何在 GLSL 中平滑淡化 2 个没有 alpha 的纹理?
- html - 使用角度路由器和 routerlinkactive 无需更改路由
- reactjs - React Development Server(启动脚本)导致与 socket.io 服务器的重复连接