gpt4 book ai didi

android - 如何让两个单独的按钮在一个 Activity 中做两件不同的事情?

转载 作者:行者123 更新时间:2023-11-30 04:59:14 25 4
gpt4 key购买 nike

我正在尝试让一个按钮计算并显示货币(这个正在运行),我正在尝试让另一个按钮打开另一个 Activity 并在那里显示货币计算。

我尝试了不同的方法来尝试为 btnSubmit(显示货币计算结果)和 btnDifferent(在显示货币计算结果的单独 Activity 中打开结果)提供两个不同的选项。

现在我只能设法计算结果并同时打开另一个 Activity 。

public class MainActivity extends AppCompatActivity {

public Spinner spnCurrency1, spnCurrency2;
public Button btnSubmit;
public Button btnDifferent;
public EditText from;
public TextView to;

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

btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnDifferent = (Button) findViewById(R.id.btnDifferent);
from = (EditText) findViewById(R.id.InputEditText);
to = (TextView) findViewById(R.id.OutputTextView);


spnCurrency1 = (Spinner) findViewById(R.id.spnCurrency1);
List<String> lstCurrency1 = new ArrayList<String>();
lstCurrency1.add("Euro");
lstCurrency1.add("USD");
lstCurrency1.add("Pound");
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lstCurrency1);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCurrency1.setAdapter(dataAdapter1);


spnCurrency2 = (Spinner) findViewById(R.id.spnCurrency2);
List<String> lstCurrency2 = new ArrayList<String>();
lstCurrency2.add("Euro");
lstCurrency2.add("USD");
lstCurrency2.add("Pound");
ArrayAdapter<String> dataAdapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lstCurrency2);
dataAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnCurrency2.setAdapter(dataAdapter2);
}

public void onClick(View v) {

int index1 = spnCurrency1.getSelectedItemPosition();
int index2 = spnCurrency2.getSelectedItemPosition();
float value = Float.parseFloat(from.getText().toString());



Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);


float ratio[] = {0.9f, 1.0f, 0.78f};
float result = value / ratio[index1] * ratio[index2];
to.setText(result + "");

}
}

最佳答案

检查 View 的 ID 并根据它执行操作:

public void onClick(View v) {
int index1 = spnCurrency1.getSelectedItemPosition();
int index2 = spnCurrency2.getSelectedItemPosition();
float value = Float.parseFloat(from.getText().toString());

float ratio[] = {0.9f, 1.0f, 0.78f};
float result = value / ratio[index1] * ratio[index2];

switch (v.getId()) {
case R.id.btnSubmit:
to.setText(result + "");
break;
case R.id.btnDifferent:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra("Result", result);
startActivity(intent);
break;
}
}

关于android - 如何让两个单独的按钮在一个 Activity 中做两件不同的事情?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58527327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com