android studio中货币转换计算器
时间: 2023-09-23 18:07:01 浏览: 103
Android Studio实现简易计算器
以下是一个简单的货币转换计算器的示例代码,使用了汇率API进行货币转换:
```
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
EditText editTextAmount;
TextView textViewResult;
String currencyFrom = "USD";
String currencyTo = "CNY";
double rate = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextAmount = findViewById(R.id.editTextAmount);
textViewResult = findViewById(R.id.textViewResult);
// 获取汇率
new GetRateTask().execute();
}
public void onClickConvert(View view) {
// 获取输入金额
String input = editTextAmount.getText().toString().trim();
if (input.isEmpty()) {
Toast.makeText(this, "请输入金额", Toast.LENGTH_SHORT).show();
return;
}
// 计算转换结果
double amount = Double.parseDouble(input);
double result = amount * rate;
// 显示转换结果
textViewResult.setText(String.format("%.2f %s = %.2f %s", amount, currencyFrom, result, currencyTo));
}
private class GetRateTask extends AsyncTask<Void, Void, String> {
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://api.exchangeratesapi.io/latest?base=" + currencyFrom + "&symbols=" + currencyTo);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s != null) {
try {
JSONObject jsonObject = new JSONObject(s);
rate = jsonObject.getJSONObject("rates").getDouble(currencyTo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
```
注意:这里使用了第三方API获取汇率,需要在`AndroidManifest.xml`文件中添加网络权限:
```
<uses-permission android:name="android.permission.INTERNET" />
```
阅读全文