first commit

This commit is contained in:
Guilherme Dias Azevedo Praça
2025-11-03 11:57:51 +00:00
commit a9da34b592
65 changed files with 3824 additions and 0 deletions

1
app/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

45
app/build.gradle.kts Normal file
View File

@@ -0,0 +1,45 @@
plugins {
alias(libs.plugins.android.application)
}
android {
namespace = "com.example.conversordemoedas2"
compileSdk = 36
defaultConfig {
applicationId = "com.example.conversordemoedas2"
minSdk = 24
targetSdk = 36
versionCode = 1
versionName = "1.0"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
isMinifyEnabled = false
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
}
dependencies {
implementation(libs.appcompat)
implementation(libs.material)
implementation(libs.activity)
implementation(libs.constraintlayout)
implementation("androidx.cardview:cardview:1.0.0")
implementation("com.google.android.material:material:1.11.0")
testImplementation(libs.junit)
androidTestImplementation(libs.ext.junit)
androidTestImplementation(libs.espresso.core)
}

21
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -0,0 +1,26 @@
package com.example.conversordemoedas2;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.conversordemoedas2", appContext.getPackageName());
}
}

View File

@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Conversordemoedas2">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SpeedConverterActivity"
android:exported="false">
</activity>
<activity
android:name=".MeasurementConverterActivity"
android:exported="false" />
</application>
</manifest>

View File

@@ -0,0 +1,86 @@
package com.example.conversordemoedas2;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Classe para gerenciar configurações e preferências do usuário
*/
public class AppPreferences {
private static final String PREFS_NAME = "CurrencyConverterPrefs";
private static final String KEY_DEFAULT_FROM_CURRENCY = "default_from_currency";
private static final String KEY_DEFAULT_TO_CURRENCY = "default_to_currency";
private static final String KEY_LAST_AMOUNT = "last_amount";
private static final String KEY_SHOW_EXCHANGE_RATE = "show_exchange_rate";
private SharedPreferences preferences;
public AppPreferences(Context context) {
preferences = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
/**
* Salva a moeda padrão de origem
*/
public void setDefaultFromCurrency(String currencyCode) {
preferences.edit().putString(KEY_DEFAULT_FROM_CURRENCY, currencyCode).apply();
}
/**
* Obtém a moeda padrão de origem
*/
public String getDefaultFromCurrency() {
return preferences.getString(KEY_DEFAULT_FROM_CURRENCY, "USD");
}
/**
* Salva a moeda padrão de destino
*/
public void setDefaultToCurrency(String currencyCode) {
preferences.edit().putString(KEY_DEFAULT_TO_CURRENCY, currencyCode).apply();
}
/**
* Obtém a moeda padrão de destino
*/
public String getDefaultToCurrency() {
return preferences.getString(KEY_DEFAULT_TO_CURRENCY, "BRL");
}
/**
* Salva o último valor digitado
*/
public void setLastAmount(double amount) {
preferences.edit().putFloat(KEY_LAST_AMOUNT, (float) amount).apply();
}
/**
* Obtém o último valor digitado
*/
public double getLastAmount() {
return preferences.getFloat(KEY_LAST_AMOUNT, 0.0f);
}
/**
* Define se deve mostrar a taxa de câmbio
*/
public void setShowExchangeRate(boolean show) {
preferences.edit().putBoolean(KEY_SHOW_EXCHANGE_RATE, show).apply();
}
/**
* Verifica se deve mostrar a taxa de câmbio
*/
public boolean getShowExchangeRate() {
return preferences.getBoolean(KEY_SHOW_EXCHANGE_RATE, true);
}
/**
* Limpa todas as preferências
*/
public void clearAll() {
preferences.edit().clear().apply();
}
}

View File

@@ -0,0 +1,52 @@
package com.example.conversordemoedas2;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Conversion {
private int id;
private String fromCurrency;
private String toCurrency;
private double amount;
private double result;
private long date;
public Conversion(int id, String fromCurrency, String toCurrency,
double amount, double result, long date) {
this.id = id;
this.fromCurrency = fromCurrency;
this.toCurrency = toCurrency;
this.amount = amount;
this.result = result;
this.date = date;
}
// Getters
public int getId() { return id; }
public String getFromCurrency() { return fromCurrency; }
public String getToCurrency() { return toCurrency; }
public double getAmount() { return amount; }
public double getResult() { return result; }
public long getDate() { return date; }
// Setters
public void setId(int id) { this.id = id; }
public void setFromCurrency(String fromCurrency) { this.fromCurrency = fromCurrency; }
public void setToCurrency(String toCurrency) { this.toCurrency = toCurrency; }
public void setAmount(double amount) { this.amount = amount; }
public void setResult(double result) { this.result = result; }
public void setDate(long date) { this.date = date; }
public String getFormattedDate() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
return sdf.format(new Date(date));
}
@Override
public String toString() {
return String.format("%.2f %s = %.2f %s (%s)",
amount, fromCurrency, result, toCurrency, getFormattedDate());
}
}

View File

@@ -0,0 +1,79 @@
package com.example.conversordemoedas2;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ConversionHistoryAdapter extends BaseAdapter {
private Context context;
private List<Conversion> conversions;
private LayoutInflater inflater;
public ConversionHistoryAdapter(Context context, List<Conversion> conversions) {
this.context = context;
this.conversions = conversions;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return conversions.size();
}
@Override
public Object getItem(int position) {
return conversions.get(position);
}
@Override
public long getItemId(int position) {
return conversions.get(position).getId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(android.R.layout.simple_list_item_2, parent, false);
holder = new ViewHolder();
holder.text1 = convertView.findViewById(android.R.id.text1);
holder.text2 = convertView.findViewById(android.R.id.text2);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Conversion conversion = conversions.get(position);
// Texto principal: conversão
String mainText = String.format("%.2f %s = %.2f %s",
conversion.getAmount(),
conversion.getFromCurrency(),
conversion.getResult(),
conversion.getToCurrency());
// Texto secundário: data
String subText = conversion.getFormattedDate();
holder.text1.setText(mainText);
holder.text2.setText(subText);
return convertView;
}
public void updateData(List<Conversion> newConversions) {
this.conversions = newConversions;
notifyDataSetChanged();
}
private static class ViewHolder {
TextView text1;
TextView text2;
}
}

View File

@@ -0,0 +1,37 @@
package com.example.conversordemoedas2;
public class Currency {
private int id;
private String code;
private String name;
private String symbol;
private double rateToUsd;
public Currency(int id, String code, String name, String symbol, double rateToUsd) {
this.id = id;
this.code = code;
this.name = name;
this.symbol = symbol;
this.rateToUsd = rateToUsd;
}
// Getters
public int getId() { return id; }
public String getCode() { return code; }
public String getName() { return name; }
public String getSymbol() { return symbol; }
public double getRateToUsd() { return rateToUsd; }
// Setters
public void setId(int id) { this.id = id; }
public void setCode(String code) { this.code = code; }
public void setName(String name) { this.name = name; }
public void setSymbol(String symbol) { this.symbol = symbol; }
public void setRateToUsd(double rateToUsd) { this.rateToUsd = rateToUsd; }
@Override
public String toString() {
return code + " - " + name + " (" + symbol + ")";
}
}

View File

@@ -0,0 +1,127 @@
package com.example.conversordemoedas2;
import android.content.Context;
import java.util.List;
public class CurrencyConverter {
private DatabaseHelper dbHelper;
public CurrencyConverter(Context context) {
this.dbHelper = new DatabaseHelper(context);
initializeDatabase();
}
private void initializeDatabase() {
// Seed additional currencies if missing
dbHelper.seedAdditionalCurrencies();
}
/**
* Converte um valor de uma moeda para outra
* @param amount Valor a ser convertido
* @param fromCurrencyCode Código da moeda de origem
* @param toCurrencyCode Código da moeda de destino
* @return Valor convertido
*/
public double convert(double amount, String fromCurrencyCode, String toCurrencyCode) {
if (fromCurrencyCode.equals(toCurrencyCode)) {
return amount;
}
Currency fromCurrency = dbHelper.getCurrencyByCode(fromCurrencyCode);
Currency toCurrency = dbHelper.getCurrencyByCode(toCurrencyCode);
if (fromCurrency == null || toCurrency == null) {
throw new IllegalArgumentException("Moeda não encontrada");
}
// Converter para USD primeiro, depois para a moeda de destino
double amountInUsd = amount / fromCurrency.getRateToUsd();
double result = amountInUsd * toCurrency.getRateToUsd();
// Salvar no histórico
dbHelper.insertConversion(fromCurrencyCode, toCurrencyCode, amount, result);
return result;
}
/**
* Obtém todas as moedas disponíveis
* @return Lista de moedas
*/
public List<Currency> getAvailableCurrencies() {
return dbHelper.getAllCurrencies();
}
/**
* Obtém o histórico de conversões
* @return Lista de conversões
*/
public List<Conversion> getConversionHistory() {
return dbHelper.getConversionHistory();
}
/**
* Limpa o histórico de conversões
*/
public void clearHistory() {
dbHelper.clearHistory();
}
/**
* Obtém uma moeda pelo código
* @param code Código da moeda
* @return Objeto Currency ou null se não encontrado
*/
public Currency getCurrencyByCode(String code) {
return dbHelper.getCurrencyByCode(code);
}
/**
* Formata um valor monetário com símbolo da moeda
* @param amount Valor
* @param currencyCode Código da moeda
* @return String formatada
*/
public String formatCurrency(double amount, String currencyCode) {
Currency currency = getCurrencyByCode(currencyCode);
if (currency != null) {
return String.format("%s %.2f", currency.getSymbol(), amount);
}
return String.format("%.2f %s", amount, currencyCode);
}
/**
* Calcula a taxa de câmbio entre duas moedas
* @param fromCurrencyCode Moeda de origem
* @param toCurrencyCode Moeda de destino
* @return Taxa de câmbio
*/
public double getExchangeRate(String fromCurrencyCode, String toCurrencyCode) {
if (fromCurrencyCode.equals(toCurrencyCode)) {
return 1.0;
}
Currency fromCurrency = dbHelper.getCurrencyByCode(fromCurrencyCode);
Currency toCurrency = dbHelper.getCurrencyByCode(toCurrencyCode);
if (fromCurrency == null || toCurrency == null) {
throw new IllegalArgumentException("Moeda não encontrada");
}
// Taxa = (rate_to_usd_destino) / (rate_to_usd_origem)
return toCurrency.getRateToUsd() / fromCurrency.getRateToUsd();
}
/**
* Insere uma conversão no histórico
* @param fromCurrency Moeda de origem
* @param toCurrency Moeda de destino
* @param amount Valor convertido
* @param result Resultado da conversão
* @return ID da conversão inserida
*/
public long insertConversion(String fromCurrency, String toCurrency, double amount, double result) {
return dbHelper.insertConversion(fromCurrency, toCurrency, amount, result);
}
}

View File

@@ -0,0 +1,121 @@
package com.example.conversordemoedas2;
import android.content.Context;
import android.util.Log;
import java.util.List;
/**
* Classe de demonstração para testar o conversor de moedas
* Esta classe pode ser usada para testar as funcionalidades do conversor
*/
public class CurrencyConverterDemo {
private static final String TAG = "CurrencyConverterDemo";
/**
* Demonstra as funcionalidades do conversor de moedas
*/
public static void runDemo(Context context) {
Log.d(TAG, "=== DEMONSTRAÇÃO DO CONVERSOR DE MOEDAS ===");
CurrencyConverter converter = new CurrencyConverter(context);
// 1. Listar todas as moedas disponíveis
Log.d(TAG, "\n1. MOEDAS DISPONÍVEIS:");
List<Currency> currencies = converter.getAvailableCurrencies();
for (Currency currency : currencies) {
Log.d(TAG, "- " + currency.toString());
}
// 2. Demonstrações de conversão
Log.d(TAG, "\n2. EXEMPLOS DE CONVERSÃO:");
// USD para BRL
try {
double result1 = converter.convert(100.0, "USD", "BRL");
Log.d(TAG, String.format("100 USD = %s", converter.formatCurrency(result1, "BRL")));
} catch (Exception e) {
Log.e(TAG, "Erro na conversão USD->BRL: " + e.getMessage());
}
// EUR para JPY
try {
double result2 = converter.convert(50.0, "EUR", "JPY");
Log.d(TAG, String.format("50 EUR = %s", converter.formatCurrency(result2, "JPY")));
} catch (Exception e) {
Log.e(TAG, "Erro na conversão EUR->JPY: " + e.getMessage());
}
// BRL para CAD
try {
double result3 = converter.convert(1000.0, "BRL", "CAD");
Log.d(TAG, String.format("1000 BRL = %s", converter.formatCurrency(result3, "CAD")));
} catch (Exception e) {
Log.e(TAG, "Erro na conversão BRL->CAD: " + e.getMessage());
}
// 3. Taxas de câmbio
Log.d(TAG, "\n3. TAXAS DE CÂMBIO:");
try {
double rate1 = converter.getExchangeRate("USD", "BRL");
Log.d(TAG, String.format("1 USD = %.4f BRL", rate1));
double rate2 = converter.getExchangeRate("EUR", "USD");
Log.d(TAG, String.format("1 EUR = %.4f USD", rate2));
double rate3 = converter.getExchangeRate("BRL", "EUR");
Log.d(TAG, String.format("1 BRL = %.4f EUR", rate3));
} catch (Exception e) {
Log.e(TAG, "Erro ao calcular taxas: " + e.getMessage());
}
// 4. Histórico de conversões
Log.d(TAG, "\n4. HISTÓRICO DE CONVERSÕES:");
List<Conversion> history = converter.getConversionHistory();
if (history.isEmpty()) {
Log.d(TAG, "Nenhuma conversão no histórico ainda.");
} else {
for (Conversion conversion : history) {
Log.d(TAG, "- " + conversion.toString());
}
}
Log.d(TAG, "\n=== FIM DA DEMONSTRAÇÃO ===");
}
/**
* Testa conversões específicas
*/
public static void testSpecificConversions(Context context) {
Log.d(TAG, "=== TESTE DE CONVERSÕES ESPECÍFICAS ===");
CurrencyConverter converter = new CurrencyConverter(context);
// Teste 1: Conversão simples
testConversion(converter, 1.0, "USD", "BRL", "1 USD para BRL");
// Teste 2: Conversão com valor alto
testConversion(converter, 10000.0, "EUR", "JPY", "10000 EUR para JPY");
// Teste 3: Conversão com valor decimal
testConversion(converter, 99.99, "GBP", "USD", "99.99 GBP para USD");
// Teste 4: Conversão para a mesma moeda
testConversion(converter, 50.0, "USD", "USD", "50 USD para USD (mesma moeda)");
Log.d(TAG, "=== FIM DOS TESTES ===");
}
private static void testConversion(CurrencyConverter converter, double amount,
String from, String to, String description) {
try {
double result = converter.convert(amount, from, to);
String formattedResult = converter.formatCurrency(result, to);
Log.d(TAG, String.format("✓ %s: %.2f %s = %s",
description, amount, from, formattedResult));
} catch (Exception e) {
Log.e(TAG, String.format("✗ %s: ERRO - %s", description, e.getMessage()));
}
}
}

View File

@@ -0,0 +1,219 @@
package com.example.conversordemoedas2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
import java.util.List;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "CurrencyConverter.db";
private static final int DATABASE_VERSION = 1;
// Tabela de moedas
private static final String TABLE_CURRENCIES = "currencies";
private static final String COLUMN_ID = "id";
private static final String COLUMN_CODE = "code";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_SYMBOL = "symbol";
private static final String COLUMN_RATE_TO_USD = "rate_to_usd";
// Tabela de histórico de conversões
private static final String TABLE_CONVERSIONS = "conversions";
private static final String COLUMN_FROM_CURRENCY = "from_currency";
private static final String COLUMN_TO_CURRENCY = "to_currency";
private static final String COLUMN_AMOUNT = "amount";
private static final String COLUMN_RESULT = "result";
private static final String COLUMN_DATE = "date";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// Criar tabela de moedas
String createCurrenciesTable = "CREATE TABLE " + TABLE_CURRENCIES + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_CODE + " TEXT UNIQUE NOT NULL, " +
COLUMN_NAME + " TEXT NOT NULL, " +
COLUMN_SYMBOL + " TEXT NOT NULL, " +
COLUMN_RATE_TO_USD + " REAL NOT NULL" +
")";
// Criar tabela de conversões
String createConversionsTable = "CREATE TABLE " + TABLE_CONVERSIONS + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FROM_CURRENCY + " TEXT NOT NULL, " +
COLUMN_TO_CURRENCY + " TEXT NOT NULL, " +
COLUMN_AMOUNT + " REAL NOT NULL, " +
COLUMN_RESULT + " REAL NOT NULL, " +
COLUMN_DATE + " TEXT NOT NULL" +
")";
db.execSQL(createCurrenciesTable);
db.execSQL(createConversionsTable);
// Inserir moedas padrão
insertDefaultCurrencies(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONVERSIONS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CURRENCIES);
onCreate(db);
}
private void insertDefaultCurrencies(SQLiteDatabase db) {
String[][] currencies = {
{"USD", "Dólar Americano", "$", "1.0"},
{"BRL", "Real Brasileiro", "R$", "5.2"},
{"EUR", "Euro", "", "0.85"},
{"GBP", "Libra Esterlina", "£", "0.73"},
{"JPY", "Iene Japonês", "¥", "110.0"},
{"CAD", "Dólar Canadense", "C$", "1.25"},
{"AUD", "Dólar Australiano", "A$", "1.35"},
{"CHF", "Franco Suíço", "CHF", "0.92"},
{"CNY", "Yuan Chinês", "¥", "6.45"},
{"MXN", "Peso Mexicano", "$", "20.0"}
};
for (String[] currency : currencies) {
ContentValues values = new ContentValues();
values.put(COLUMN_CODE, currency[0]);
values.put(COLUMN_NAME, currency[1]);
values.put(COLUMN_SYMBOL, currency[2]);
values.put(COLUMN_RATE_TO_USD, Double.parseDouble(currency[3]));
db.insert(TABLE_CURRENCIES, null, values);
}
}
// Métodos para gerenciar moedas
public List<Currency> getAllCurrencies() {
List<Currency> currencies = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CURRENCIES, null, null, null, null, null, COLUMN_NAME);
if (cursor.moveToFirst()) {
do {
Currency currency = new Currency(
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CODE)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_SYMBOL)),
cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_RATE_TO_USD))
);
currencies.add(currency);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return currencies;
}
public Currency getCurrencyByCode(String code) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CURRENCIES, null, COLUMN_CODE + "=?",
new String[]{code}, null, null, null);
Currency currency = null;
if (cursor.moveToFirst()) {
currency = new Currency(
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_CODE)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_NAME)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_SYMBOL)),
cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_RATE_TO_USD))
);
}
cursor.close();
db.close();
return currency;
}
public void seedAdditionalCurrencies() {
SQLiteDatabase db = this.getWritableDatabase();
String[][] more = new String[][]{
{"ARS","Peso Argentino","$","970.0"},
{"CLP","Peso Chileno","$","920.0"},
{"COP","Peso Colombiano","$","4100.0"},
{"INR","Rúpia Indiana","","83.0"},
{"ZAR","Rand Sul-Africano","R","18.5"},
{"TRY","Lira Turca","","34.0"},
{"RUB","Rublo Russo","","95.0"},
{"KRW","Won Sul-Coreano","","1350.0"},
{"SEK","Coroa Sueca","kr","10.5"},
{"NOK","Coroa Norueguesa","kr","10.8"},
{"DKK","Coroa Dinamarquesa","kr","6.9"},
{"PLN","Zlóti Polonês","","4.0"},
{"CZK","Coroa Checa","","23.0"},
{"HUF","Florim Húngaro","Ft","370.0"},
{"ILS","Novo Shekel Israelense","","3.8"},
{"AED","Dirham dos EAU","د.إ","3.67"},
{"SAR","Rial Saudita","","3.75"},
{"NZD","Dólar Neozelandês","NZ$","1.60"},
{"SGD","Dólar de Cingapura","S$","1.35"},
{"HKD","Dólar de Hong Kong","HK$","7.80"}
};
for (String[] c : more) {
ContentValues v = new ContentValues();
v.put(COLUMN_CODE, c[0]);
v.put(COLUMN_NAME, c[1]);
v.put(COLUMN_SYMBOL, c[2]);
v.put(COLUMN_RATE_TO_USD, Double.parseDouble(c[3]));
db.insertWithOnConflict(TABLE_CURRENCIES, null, v, SQLiteDatabase.CONFLICT_IGNORE);
}
db.close();
}
// Métodos para gerenciar conversões
public long insertConversion(String fromCurrency, String toCurrency,
double amount, double result) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_FROM_CURRENCY, fromCurrency);
values.put(COLUMN_TO_CURRENCY, toCurrency);
values.put(COLUMN_AMOUNT, amount);
values.put(COLUMN_RESULT, result);
values.put(COLUMN_DATE, System.currentTimeMillis());
long id = db.insert(TABLE_CONVERSIONS, null, values);
db.close();
return id;
}
public List<Conversion> getConversionHistory() {
List<Conversion> conversions = new ArrayList<>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONVERSIONS, null, null, null, null, null,
COLUMN_DATE + " DESC", "50");
if (cursor.moveToFirst()) {
do {
Conversion conversion = new Conversion(
cursor.getInt(cursor.getColumnIndexOrThrow(COLUMN_ID)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_FROM_CURRENCY)),
cursor.getString(cursor.getColumnIndexOrThrow(COLUMN_TO_CURRENCY)),
cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_AMOUNT)),
cursor.getDouble(cursor.getColumnIndexOrThrow(COLUMN_RESULT)),
cursor.getLong(cursor.getColumnIndexOrThrow(COLUMN_DATE))
);
conversions.add(conversion);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return conversions;
}
public void clearHistory() {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONVERSIONS, null, null);
db.close();
}
}

View File

@@ -0,0 +1,266 @@
package com.example.conversordemoedas2;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private CurrencyConverter currencyConverter;
private TextInputEditText amountInput;
private Spinner fromCurrencySpinner;
private Spinner toCurrencySpinner;
private TextView resultText;
private TextView exchangeRateText;
private MaterialButton clearHistoryButton;
private ListView historyListView;
private ImageView swapButton;
private MaterialButton speedConverterButton;
private List<Currency> currencies;
private ConversionHistoryAdapter historyAdapter;
private boolean isUpdating = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
initializeViews();
initializeCurrencyConverter();
setupSpinners();
setupListeners();
loadHistory();
// Executar demonstração no log (opcional)
// CurrencyConverterDemo.runDemo(this);
}
private void initializeViews() {
amountInput = findViewById(R.id.amountInput);
fromCurrencySpinner = findViewById(R.id.fromCurrencySpinner);
toCurrencySpinner = findViewById(R.id.toCurrencySpinner);
resultText = findViewById(R.id.resultText);
exchangeRateText = findViewById(R.id.exchangeRateText);
clearHistoryButton = findViewById(R.id.clearHistoryButton);
historyListView = findViewById(R.id.historyListView);
swapButton = findViewById(R.id.swapButton);
speedConverterButton = findViewById(R.id.speedConverterButton);
}
private void initializeCurrencyConverter() {
currencyConverter = new CurrencyConverter(this);
currencies = currencyConverter.getAvailableCurrencies();
}
private void setupSpinners() {
// Criar lista de strings para os spinners
List<String> currencyStrings = new ArrayList<>();
for (Currency currency : currencies) {
currencyStrings.add(currency.toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, currencyStrings);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromCurrencySpinner.setAdapter(adapter);
toCurrencySpinner.setAdapter(adapter);
// Selecionar USD como padrão para origem e BRL para destino
for (int i = 0; i < currencies.size(); i++) {
if (currencies.get(i).getCode().equals("USD")) {
fromCurrencySpinner.setSelection(i);
}
if (currencies.get(i).getCode().equals("BRL")) {
toCurrencySpinner.setSelection(i);
}
}
// Atualizar conversão quando as moedas mudarem
fromCurrencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!isUpdating) {
updateConversion();
updateExchangeRate();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
toCurrencySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!isUpdating) {
updateConversion();
updateExchangeRate();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
private void setupListeners() {
// Conversão automática quando o texto muda
amountInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
updateConversion();
}
});
// Botão de trocar moedas
swapButton.setOnClickListener(v -> swapCurrencies());
// Botão limpar histórico
clearHistoryButton.setOnClickListener(v -> clearHistory());
// Botão conversor de velocidade
speedConverterButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, SpeedConverterActivity.class);
startActivity(intent);
});
// Botão conversor de medidas
MaterialButton measurementConverterButton = findViewById(R.id.measurementConverterButton);
measurementConverterButton.setOnClickListener(v -> {
Intent intent = new Intent(MainActivity.this, MeasurementConverterActivity.class);
startActivity(intent);
});
}
private void updateConversion() {
String amountString = amountInput.getText().toString().trim();
if (TextUtils.isEmpty(amountString)) {
resultText.setText("Digite um valor para converter");
resultText.setTextColor(getResources().getColor(R.color.text_secondary));
return;
}
try {
double amount = Double.parseDouble(amountString);
if (amount <= 0) {
resultText.setText("Digite um valor positivo");
resultText.setTextColor(getResources().getColor(R.color.error_color));
return;
}
Currency fromCurrency = currencies.get(fromCurrencySpinner.getSelectedItemPosition());
Currency toCurrency = currencies.get(toCurrencySpinner.getSelectedItemPosition());
double result = currencyConverter.convert(amount, fromCurrency.getCode(), toCurrency.getCode());
// Mostrar resultado com animação
String formattedResult = currencyConverter.formatCurrency(result, toCurrency.getCode());
resultText.setText(formattedResult);
resultText.setTextColor(getResources().getColor(R.color.primary_color));
// Animação suave
resultText.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
// Salvar no histórico apenas se for uma conversão válida
if (amount > 0) {
currencyConverter.insertConversion(fromCurrency.getCode(), toCurrency.getCode(), amount, result);
loadHistory();
}
} catch (NumberFormatException e) {
resultText.setText("Digite um valor válido");
resultText.setTextColor(getResources().getColor(R.color.error_color));
} catch (Exception e) {
resultText.setText("Erro na conversão");
resultText.setTextColor(getResources().getColor(R.color.error_color));
}
}
private void swapCurrencies() {
isUpdating = true;
int fromPosition = fromCurrencySpinner.getSelectedItemPosition();
int toPosition = toCurrencySpinner.getSelectedItemPosition();
fromCurrencySpinner.setSelection(toPosition);
toCurrencySpinner.setSelection(fromPosition);
// Animação do botão
swapButton.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
isUpdating = false;
// Atualizar conversão após a troca
updateConversion();
updateExchangeRate();
Toast.makeText(this, "Moedas trocadas!", Toast.LENGTH_SHORT).show();
}
private void updateExchangeRate() {
try {
Currency fromCurrency = currencies.get(fromCurrencySpinner.getSelectedItemPosition());
Currency toCurrency = currencies.get(toCurrencySpinner.getSelectedItemPosition());
double rate = currencyConverter.getExchangeRate(fromCurrency.getCode(), toCurrency.getCode());
String rateText = String.format("1 %s = %.4f %s",
fromCurrency.getCode(), rate, toCurrency.getCode());
exchangeRateText.setText(rateText);
} catch (Exception e) {
exchangeRateText.setText("Erro ao calcular taxa");
}
}
private void loadHistory() {
List<Conversion> history = currencyConverter.getConversionHistory();
historyAdapter = new ConversionHistoryAdapter(this, history);
historyListView.setAdapter(historyAdapter);
}
private void clearHistory() {
currencyConverter.clearHistory();
loadHistory();
Toast.makeText(this, "Histórico limpo", Toast.LENGTH_SHORT).show();
}
}

View File

@@ -0,0 +1,93 @@
package com.example.conversordemoedas2;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class MeasurementConverter {
private static final String CAT_LENGTH = "Comprimento";
private static final String CAT_WEIGHT = "Peso";
private static final String CAT_TEMPERATURE = "Temperatura";
private static final List<String> LENGTH_UNITS = Arrays.asList("mm","cm","m","km","in","ft","yd","mi");
private static final List<String> WEIGHT_UNITS = Arrays.asList("mg","g","kg","t","oz","lb");
private static final List<String> TEMP_UNITS = Arrays.asList("°C","°F","K");
private static final Map<String, Double> LENGTH_TO_METER = new LinkedHashMap<>();
private static final Map<String, Double> WEIGHT_TO_KG = new LinkedHashMap<>();
static {
// Comprimento -> metros
LENGTH_TO_METER.put("mm", 0.001);
LENGTH_TO_METER.put("cm", 0.01);
LENGTH_TO_METER.put("m", 1.0);
LENGTH_TO_METER.put("km", 1000.0);
LENGTH_TO_METER.put("in", 0.0254);
LENGTH_TO_METER.put("ft", 0.3048);
LENGTH_TO_METER.put("yd", 0.9144);
LENGTH_TO_METER.put("mi", 1609.344);
// Peso -> quilogramas
WEIGHT_TO_KG.put("mg", 0.000001);
WEIGHT_TO_KG.put("g", 0.001);
WEIGHT_TO_KG.put("kg", 1.0);
WEIGHT_TO_KG.put("t", 1000.0);
WEIGHT_TO_KG.put("oz", 0.028349523125);
WEIGHT_TO_KG.put("lb", 0.45359237);
}
public List<String> getUnitsForCategory(String category) {
if (CAT_LENGTH.equals(category)) return new ArrayList<>(LENGTH_UNITS);
if (CAT_WEIGHT.equals(category)) return new ArrayList<>(WEIGHT_UNITS);
if (CAT_TEMPERATURE.equals(category)) return new ArrayList<>(TEMP_UNITS);
return new ArrayList<>();
}
public double convert(String category, double value, String from, String to) {
if (from.equals(to)) return value;
if (CAT_LENGTH.equals(category)) {
double meters = value * LENGTH_TO_METER.get(from);
return meters / LENGTH_TO_METER.get(to);
}
if (CAT_WEIGHT.equals(category)) {
double kg = value * WEIGHT_TO_KG.get(from);
return kg / WEIGHT_TO_KG.get(to);
}
if (CAT_TEMPERATURE.equals(category)) {
// normalize to Celsius
double c;
if ("°C".equals(from)) c = value;
else if ("°F".equals(from)) c = (value - 32.0) * 5.0 / 9.0;
else c = value - 273.15; // K -> C
if ("°C".equals(to)) return c;
if ("°F".equals(to)) return c * 9.0 / 5.0 + 32.0;
return c + 273.15; // to K
}
throw new IllegalArgumentException("Categoria inválida");
}
public double rate(String category, String from, String to) {
if (from.equals(to)) return 1.0;
if (CAT_LENGTH.equals(category)) {
return LENGTH_TO_METER.get(from) / LENGTH_TO_METER.get(to);
}
if (CAT_WEIGHT.equals(category)) {
return WEIGHT_TO_KG.get(from) / WEIGHT_TO_KG.get(to);
}
if (CAT_TEMPERATURE.equals(category)) {
// temperature rates aren't constant; show delta conversion for 1 unit
return convert(category, 1.0, from, to);
}
return 1.0;
}
public String format(String category, double value, String unit) {
if (CAT_TEMPERATURE.equals(category)) {
return String.format("%.2f %s", value, unit);
}
return String.format("%.4f %s", value, unit);
}
}

View File

@@ -0,0 +1,170 @@
package com.example.conversordemoedas2;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.TextUtils;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import com.google.android.material.textfield.TextInputEditText;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MeasurementConverterActivity extends AppCompatActivity {
private MeasurementConverter measurementConverter;
private Spinner categorySpinner;
private Spinner fromUnitSpinner;
private Spinner toUnitSpinner;
private TextInputEditText amountInput;
private TextView resultText;
private TextView rateText;
private List<String> categories;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.fragment_measurement_converter);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.measureMain), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
initializeViews();
initializeConverter();
setupCategorySpinner();
setupListeners();
}
private void initializeViews() {
categorySpinner = findViewById(R.id.categorySpinner);
fromUnitSpinner = findViewById(R.id.measureFromUnitSpinner);
toUnitSpinner = findViewById(R.id.measureToUnitSpinner);
amountInput = findViewById(R.id.measureAmountInput);
resultText = findViewById(R.id.measureResultText);
rateText = findViewById(R.id.measureRateText);
findViewById(R.id.openCurrencyConverterButton).setOnClickListener(v -> {
startActivity(new android.content.Intent(this, MainActivity.class));
});
findViewById(R.id.openSpeedConverterButton).setOnClickListener(v -> {
startActivity(new android.content.Intent(this, SpeedConverterActivity.class));
});
}
private void initializeConverter() {
measurementConverter = new MeasurementConverter();
categories = new ArrayList<>(Arrays.asList("Comprimento", "Peso", "Temperatura"));
}
private void setupCategorySpinner() {
ArrayAdapter<String> categoryAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, categories);
categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
categorySpinner.setAdapter(categoryAdapter);
categorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) {
populateUnits();
updateConversion();
updateRate();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
private void populateUnits() {
String category = (String) categorySpinner.getSelectedItem();
List<String> units = measurementConverter.getUnitsForCategory(category);
ArrayAdapter<String> unitsAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, units);
unitsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromUnitSpinner.setAdapter(unitsAdapter);
toUnitSpinner.setAdapter(unitsAdapter);
if (!units.isEmpty()) {
fromUnitSpinner.setSelection(0);
toUnitSpinner.setSelection(Math.min(1, units.size() - 1));
}
fromUnitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) {
updateConversion();
updateRate();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
toUnitSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, android.view.View view, int position, long id) {
updateConversion();
updateRate();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
private void setupListeners() {
amountInput.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override public void afterTextChanged(Editable s) { updateConversion(); }
});
}
private void updateConversion() {
String input = amountInput.getText() != null ? amountInput.getText().toString().trim() : "";
if (TextUtils.isEmpty(input)) {
resultText.setText("Digite um valor para converter");
resultText.setTextColor(getResources().getColor(R.color.text_secondary));
return;
}
try {
double value = Double.parseDouble(input);
String category = (String) categorySpinner.getSelectedItem();
String from = (String) fromUnitSpinner.getSelectedItem();
String to = (String) toUnitSpinner.getSelectedItem();
double result = measurementConverter.convert(category, value, from, to);
String formatted = measurementConverter.format(category, result, to);
resultText.setText(formatted);
resultText.setTextColor(getResources().getColor(R.color.accent_color));
resultText.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
} catch (NumberFormatException e) {
resultText.setText("Digite um valor válido");
resultText.setTextColor(getResources().getColor(R.color.error_color));
} catch (Exception e) {
resultText.setText("Erro na conversão");
resultText.setTextColor(getResources().getColor(R.color.error_color));
}
}
private void updateRate() {
try {
String category = (String) categorySpinner.getSelectedItem();
String from = (String) fromUnitSpinner.getSelectedItem();
String to = (String) toUnitSpinner.getSelectedItem();
double rate = measurementConverter.rate(category, from, to);
rateText.setText(String.format("1 %s = %.6f %s", from, rate, to));
} catch (Exception e) {
rateText.setText("Selecione as unidades");
}
}
}

View File

@@ -0,0 +1,156 @@
package com.example.conversordemoedas2;
import android.content.Context;
import java.util.ArrayList;
import java.util.List;
public class SpeedConverter {
private DatabaseHelper dbHelper;
// Unidades de velocidade com fatores de conversão para m/s (metros por segundo)
private static final Object[][] SPEED_UNITS = {
// ID, Símbolo, Fator para m/s, Descrição
{1, "m/s", 1.0, "Metros por segundo"},
{2, "km/h", 0.277778, "Quilômetros por hora"},
{3, "mph", 0.44704, "Milhas por hora"},
{4, "ft/s", 0.3048, "Pés por segundo"},
{5, "knot", 0.514444, "Nós"},
{6, "mach", 343.0, "Mach"},
{7, "c", 299792458.0, "Velocidade da luz"},
{8, "fps", 0.3048, "Frames por segundo"},
{9, "rpm", 0.10472, "Rotações por minuto"},
{10, "deg/s", 0.0174533, "Graus por segundo"}
};
public SpeedConverter(Context context) {
this.dbHelper = new DatabaseHelper(context);
}
/**
* Converte velocidade de uma unidade para outra
* @param value Valor a ser convertido
* @param fromUnit Unidade de origem
* @param toUnit Unidade de destino
* @return Valor convertido
*/
public double convert(double value, String fromUnit, String toUnit) {
if (fromUnit.equals(toUnit)) {
return value;
}
double fromFactor = getFactor(fromUnit);
double toFactor = getFactor(toUnit);
if (fromFactor == 0 || toFactor == 0) {
throw new IllegalArgumentException("Unidade não encontrada");
}
// Converter para m/s primeiro, depois para a unidade de destino
double valueInMs = value * fromFactor;
double result = valueInMs / toFactor;
return result;
}
/**
* Obtém o fator de conversão para uma unidade
* @param unit Unidade de velocidade
* @return Fator de conversão
*/
private double getFactor(String unit) {
for (Object[] speedUnit : SPEED_UNITS) {
if (speedUnit[1].equals(unit)) {
return (Double) speedUnit[2];
}
}
return 0;
}
/**
* Obtém todas as unidades de velocidade disponíveis
* @return Lista de unidades
*/
public List<SpeedUnit> getAvailableUnits() {
List<SpeedUnit> units = new ArrayList<>();
for (Object[] speedUnit : SPEED_UNITS) {
units.add(new SpeedUnit(
(int) speedUnit[0],
(String) speedUnit[1],
(String) speedUnit[3],
(Double) speedUnit[2]
));
}
return units;
}
/**
* Obtém uma unidade pelo código
* @param code Código da unidade
* @return Objeto SpeedUnit ou null se não encontrado
*/
public SpeedUnit getUnitByCode(String code) {
for (Object[] speedUnit : SPEED_UNITS) {
if (speedUnit[1].equals(code)) {
return new SpeedUnit(
(int) speedUnit[0],
(String) speedUnit[1],
(String) speedUnit[3],
(Double) speedUnit[2]
);
}
}
return null;
}
/**
* Formata um valor de velocidade com símbolo da unidade
* @param value Valor
* @param unitCode Código da unidade
* @return String formatada
*/
public String formatSpeed(double value, String unitCode) {
SpeedUnit unit = getUnitByCode(unitCode);
if (unit != null) {
return String.format("%.2f %s", value, unit.getSymbol());
}
return String.format("%.2f %s", value, unitCode);
}
/**
* Calcula a taxa de conversão entre duas unidades
* @param fromUnit Unidade de origem
* @param toUnit Unidade de destino
* @return Taxa de conversão
*/
public double getConversionRate(String fromUnit, String toUnit) {
if (fromUnit.equals(toUnit)) {
return 1.0;
}
double fromFactor = getFactor(fromUnit);
double toFactor = getFactor(toUnit);
if (fromFactor == 0 || toFactor == 0) {
throw new IllegalArgumentException("Unidade não encontrada");
}
return fromFactor / toFactor;
}
/**
* Obtém exemplos de conversão para demonstração
* @return Lista de exemplos
*/
public List<String> getExamples() {
List<String> examples = new ArrayList<>();
examples.add("🚗 100 km/h = 27.78 m/s");
examples.add("✈️ 500 mph = 223.52 m/s");
examples.add("🏃 10 m/s = 36 km/h");
examples.add("🚢 20 knot = 10.29 m/s");
examples.add("🚀 1 mach = 343 m/s");
return examples;
}
}

View File

@@ -0,0 +1,219 @@
package com.example.conversordemoedas2;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.textfield.TextInputEditText;
import java.util.ArrayList;
import java.util.List;
public class SpeedConverterActivity extends AppCompatActivity {
private SpeedConverter speedConverter;
private TextInputEditText speedAmountInput;
private Spinner fromSpeedSpinner;
private Spinner toSpeedSpinner;
private TextView speedResultText;
private TextView speedRateText;
private ImageView speedSwapButton;
private List<SpeedUnit> speedUnits;
private boolean isUpdating = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.fragment_speed_converter);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.speedMain), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
// Removida Toolbar!
findViewById(R.id.currencyConverterButton).setOnClickListener(v -> finish());
initializeViews();
initializeSpeedConverter();
setupSpinners();
setupListeners();
}
private void initializeViews() {
speedAmountInput = findViewById(R.id.speedAmountInput);
fromSpeedSpinner = findViewById(R.id.speedFromUnitSpinner);
toSpeedSpinner = findViewById(R.id.speedToUnitSpinner);
speedResultText = findViewById(R.id.speedResultText);
speedRateText = findViewById(R.id.speedRateText);
speedSwapButton = findViewById(R.id.speedSwapButton);
}
private void initializeSpeedConverter() {
speedConverter = new SpeedConverter(this);
speedUnits = speedConverter.getAvailableUnits();
}
private void setupSpinners() {
// Criar lista de strings para os spinners
List<String> unitStrings = new ArrayList<>();
for (SpeedUnit unit : speedUnits) {
unitStrings.add(unit.toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_spinner_item, unitStrings);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
fromSpeedSpinner.setAdapter(adapter);
toSpeedSpinner.setAdapter(adapter);
// Selecionar m/s como padrão para origem e km/h para destino
for (int i = 0; i < speedUnits.size(); i++) {
if (speedUnits.get(i).getSymbol().equals("m/s")) {
fromSpeedSpinner.setSelection(i);
}
if (speedUnits.get(i).getSymbol().equals("km/h")) {
toSpeedSpinner.setSelection(i);
}
}
// Atualizar conversão quando as unidades mudarem
fromSpeedSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!isUpdating) {
updateConversion();
updateRate();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
toSpeedSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!isUpdating) {
updateConversion();
updateRate();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {}
});
}
private void setupListeners() {
// Conversão automática quando o texto muda
speedAmountInput.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
updateConversion();
}
});
// Botão de trocar unidades
speedSwapButton.setOnClickListener(v -> swapUnits());
}
private void updateConversion() {
String amountString = speedAmountInput.getText().toString().trim();
if (TextUtils.isEmpty(amountString)) {
speedResultText.setText("Digite um valor para converter");
speedResultText.setTextColor(getResources().getColor(R.color.text_secondary));
return;
}
try {
double amount = Double.parseDouble(amountString);
if (amount < 0) {
speedResultText.setText("Digite um valor positivo");
speedResultText.setTextColor(getResources().getColor(R.color.error_color));
return;
}
SpeedUnit fromUnit = speedUnits.get(fromSpeedSpinner.getSelectedItemPosition());
SpeedUnit toUnit = speedUnits.get(toSpeedSpinner.getSelectedItemPosition());
double result = speedConverter.convert(amount, fromUnit.getSymbol(), toUnit.getSymbol());
// Mostrar resultado com animação
String formattedResult = speedConverter.formatSpeed(result, toUnit.getSymbol());
speedResultText.setText(formattedResult);
speedResultText.setTextColor(getResources().getColor(R.color.accent_color));
// Animação suave
speedResultText.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
} catch (NumberFormatException e) {
speedResultText.setText("Digite um valor válido");
speedResultText.setTextColor(getResources().getColor(R.color.error_color));
} catch (Exception e) {
speedResultText.setText("Erro na conversão");
speedResultText.setTextColor(getResources().getColor(R.color.error_color));
}
}
private void swapUnits() {
isUpdating = true;
int fromPosition = fromSpeedSpinner.getSelectedItemPosition();
int toPosition = toSpeedSpinner.getSelectedItemPosition();
fromSpeedSpinner.setSelection(toPosition);
toSpeedSpinner.setSelection(fromPosition);
// Animação do botão
speedSwapButton.startAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
isUpdating = false;
// Atualizar conversão após a troca
updateConversion();
updateRate();
}
private void updateRate() {
try {
SpeedUnit fromUnit = speedUnits.get(fromSpeedSpinner.getSelectedItemPosition());
SpeedUnit toUnit = speedUnits.get(toSpeedSpinner.getSelectedItemPosition());
double rate = speedConverter.getConversionRate(fromUnit.getSymbol(), toUnit.getSymbol());
String rateText = String.format("1 %s = %.4f %s",
fromUnit.getSymbol(), rate, toUnit.getSymbol());
speedRateText.setText(rateText);
} catch (Exception e) {
speedRateText.setText("Erro ao calcular taxa");
}
}
}

View File

@@ -0,0 +1,36 @@
package com.example.conversordemoedas2;
public class SpeedUnit {
private int id;
private String symbol;
private String name;
private double factorToMs;
public SpeedUnit(int id, String symbol, String name, double factorToMs) {
this.id = id;
this.symbol = symbol;
this.name = name;
this.factorToMs = factorToMs;
}
// Getters
public int getId() { return id; }
public String getSymbol() { return symbol; }
public String getName() { return name; }
public double getFactorToMs() { return factorToMs; }
// Setters
public void setId(int id) { this.id = id; }
public void setSymbol(String symbol) { this.symbol = symbol; }
public void setName(String name) { this.name = name; }
public void setFactorToMs(double factorToMs) { this.factorToMs = factorToMs; }
@Override
public String toString() {
return symbol + " - " + name;
}
}

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/primary_color" />
<stroke android:width="2dp" android:color="@color/white" />
</shape>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="@color/primary_color" />
<stroke android:width="2dp" android:color="@color/white" />
</shape>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFF"
android:pathData="M20,11H7.83l5.58-5.59L12,4l-8,8 8,8 1.41-1.41L7.83,13H20v-2z"/>
</vector>

View File

@@ -0,0 +1,170 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path
android:fillColor="#3DDC84"
android:pathData="M0,0h108v108h-108z" />
<path
android:fillColor="#00000000"
android:pathData="M9,0L9,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,0L19,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,0L29,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,0L39,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,0L49,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,0L59,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,0L69,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,0L79,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M89,0L89,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M99,0L99,108"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,9L108,9"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,19L108,19"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,29L108,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,39L108,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,49L108,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,59L108,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,69L108,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,79L108,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,89L108,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M0,99L108,99"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,29L89,29"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,39L89,39"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,49L89,49"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,59L89,59"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,69L89,69"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M19,79L89,79"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M29,19L29,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M39,19L39,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M49,19L49,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M59,19L59,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M69,19L69,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
<path
android:fillColor="#00000000"
android:pathData="M79,19L79,89"
android:strokeWidth="0.8"
android:strokeColor="#33FFFFFF" />
</vector>

View File

@@ -0,0 +1,30 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<path android:pathData="M31,63.928c0,0 6.4,-11 12.1,-13.1c7.2,-2.6 26,-1.4 26,-1.4l38.1,38.1L107,108.928l-32,-1L31,63.928z">
<aapt:attr name="android:fillColor">
<gradient
android:endX="85.84757"
android:endY="92.4963"
android:startX="42.9492"
android:startY="49.59793"
android:type="linear">
<item
android:color="#44000000"
android:offset="0.0" />
<item
android:color="#00000000"
android:offset="1.0" />
</gradient>
</aapt:attr>
</path>
<path
android:fillColor="#FFFFFF"
android:fillType="nonZero"
android:pathData="M65.3,45.828l3.8,-6.6c0.2,-0.4 0.1,-0.9 -0.3,-1.1c-0.4,-0.2 -0.9,-0.1 -1.1,0.3l-3.9,6.7c-6.3,-2.8 -13.4,-2.8 -19.7,0l-3.9,-6.7c-0.2,-0.4 -0.7,-0.5 -1.1,-0.3C38.8,38.328 38.7,38.828 38.9,39.228l3.8,6.6C36.2,49.428 31.7,56.028 31,63.928h46C76.3,56.028 71.8,49.428 65.3,45.828zM43.4,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2c-0.3,-0.7 -0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C45.3,56.528 44.5,57.328 43.4,57.328L43.4,57.328zM64.6,57.328c-0.8,0 -1.5,-0.5 -1.8,-1.2s-0.1,-1.5 0.4,-2.1c0.5,-0.5 1.4,-0.7 2.1,-0.4c0.7,0.3 1.2,1 1.2,1.8C66.5,56.528 65.6,57.328 64.6,57.328L64.6,57.328z"
android:strokeWidth="1"
android:strokeColor="#00000000" />
</vector>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="@color/primary_color">
<path
android:fillColor="@android:color/white"
android:pathData="M16,17.01V10h-2v7.01h-3L15,21l4,-3.99h-3zM9,3L5,6.99h3V14h2V6.99h3L9,3z"/>
</vector>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@android:color/white" />
<stroke android:width="1dp" android:color="@color/primary_color" />
<corners android:radius="8dp" />
</shape>

View File

@@ -0,0 +1,338 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:background="@color/background_gradient"
tools:context=".MainActivity">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="20dp">
<!-- Header com título e ícone -->
<androidx.cardview.widget.CardView
android:id="@+id/headerCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="24dp"
app:cardCornerRadius="20dp"
app:cardElevation="8dp"
app:cardBackgroundColor="@color/primary_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="💱"
android:textSize="48sp"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conversor de Moedas"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@android:color/white"
android:fontFamily="sans-serif-medium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conversão em tempo real"
android:textSize="14sp"
android:textColor="@color/white_transparent"
android:layout_marginTop="4dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Botão para Conversor de Velocidade -->
<com.google.android.material.button.MaterialButton
android:id="@+id/speedConverterButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:text="🏃 Conversor de Velocidade"
android:textSize="16sp"
android:textStyle="bold"
android:padding="16dp"
app:cornerRadius="12dp"
app:backgroundTint="@color/accent_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/headerCard" />
<com.google.android.material.button.MaterialButton
android:id="@+id/measurementConverterButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="20dp"
android:text="📏 Conversor de Medidas"
android:textSize="16sp"
android:textStyle="bold"
android:padding="16dp"
app:cornerRadius="12dp"
app:backgroundTint="@color/primary_color"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/speedConverterButton" />
<!-- Card de Conversão Principal -->
<androidx.cardview.widget.CardView
android:id="@+id/conversionCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/measurementConverterButton">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<!-- Valor de Entrada -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="💰 Valor"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-medium" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Digite o valor"
app:boxStrokeColor="@color/primary_color"
app:hintTextColor="@color/primary_color"
app:startIconDrawable="@android:drawable/ic_menu_edit"
app:startIconTint="@color/primary_color">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/amountInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:textSize="20sp"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-light" />
</com.google.android.material.textfield.TextInputLayout>
<!-- Seleção de Moedas -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<!-- Moeda de Origem -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginEnd="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🔄 De"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<Spinner
android:id="@+id/fromCurrencySpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
<!-- Botão de Troca -->
<ImageView
android:id="@+id/swapButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginHorizontal="8dp"
android:src="@drawable/ic_swap"
android:background="@drawable/circle_background"
android:padding="12dp"
android:contentDescription="Trocar moedas" />
<!-- Moeda de Destino -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🎯 Para"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<Spinner
android:id="@+id/toCurrencySpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
</LinearLayout>
<!-- Resultado -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
app:cardCornerRadius="12dp"
app:cardElevation="2dp"
app:cardBackgroundColor="@color/result_background">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="💵 Resultado"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<TextView
android:id="@+id/resultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Digite um valor para converter"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@color/primary_color"
android:textAlignment="center"
android:fontFamily="sans-serif-light" />
<TextView
android:id="@+id/exchangeRateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Selecione as moedas"
android:textSize="12sp"
android:textColor="@color/text_secondary"
android:textAlignment="center" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Card de Histórico -->
<androidx.cardview.widget.CardView
android:id="@+id/historyCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/conversionCard">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="📊 Histórico"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-medium" />
<com.google.android.material.button.MaterialButton
android:id="@+id/clearHistoryButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🗑️ Limpar"
android:textSize="12sp"
android:backgroundTint="@color/error_color"
app:cornerRadius="20dp" />
</LinearLayout>
<ListView
android:id="@+id/historyListView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="12dp"
android:divider="@android:color/transparent"
android:dividerHeight="8dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>

View File

@@ -0,0 +1,214 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:background="@color/background_gradient"
tools:context=".MeasurementConverterActivity">
<LinearLayout
android:id="@+id/measureMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<!-- Header -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:cardCornerRadius="20dp"
app:cardElevation="8dp"
app:cardBackgroundColor="@color/primary_color">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="📏"
android:textSize="48sp"
android:layout_marginBottom="8dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conversor de Medidas"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@android:color/white"
android:fontFamily="sans-serif-medium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Comprimento, Peso e Temperatura"
android:textSize="14sp"
android:textColor="@color/white_transparent"
android:layout_marginTop="4dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Botões de navegação -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="2">
<com.google.android.material.button.MaterialButton
android:id="@+id/openCurrencyConverterButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="💱 Conversor de Moedas"
android:textSize="14sp"
android:textStyle="bold"
android:padding="14dp"
app:cornerRadius="12dp"
app:backgroundTint="@color/primary_color" />
<View
android:layout_width="8dp"
android:layout_height="0dp" />
<com.google.android.material.button.MaterialButton
android:id="@+id/openSpeedConverterButton"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="🏃 Conversor de Velocidade"
android:textSize="14sp"
android:textStyle="bold"
android:padding="14dp"
app:cornerRadius="12dp"
app:backgroundTint="@color/accent_color" />
</LinearLayout>
<!-- Categoria -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Categoria"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary" />
<Spinner
android:id="@+id/categorySpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Conversão -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valor"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Digite o valor">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/measureAmountInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="12dp">
<Spinner
android:id="@+id/measureFromUnitSpinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/spinner_background"
android:padding="12dp" />
<Spinner
android:id="@+id/measureToUnitSpinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginStart="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
<TextView
android:id="@+id/measureResultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Digite um valor para converter"
android:textSize="22sp"
android:textStyle="bold"
android:textColor="@color/primary_color" />
<TextView
android:id="@+id/measureRateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="6dp"
android:text="Selecione as unidades"
android:textSize="12sp"
android:textColor="@color/text_secondary" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>

View File

@@ -0,0 +1,300 @@
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:background="@color/background_gradient"
tools:context=".MainActivity">
<LinearLayout
android:id="@+id/speedMain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<!-- Header com título e ícone -->
<androidx.cardview.widget.CardView
android:id="@+id/speedHeaderCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
app:cardCornerRadius="20dp"
app:cardElevation="8dp"
app:cardBackgroundColor="@color/accent_color">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🏃"
android:textSize="48sp"
android:layout_marginBottom="8dp" />
<TextView
android:id="@+id/speedTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conversor de Velocidade"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@android:color/white"
android:fontFamily="sans-serif-medium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Conversão em tempo real"
android:textSize="14sp"
android:textColor="@color/white_transparent"
android:layout_marginTop="4dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Botão para retornar ao conversor de moedas -->
<com.google.android.material.button.MaterialButton
android:id="@+id/currencyConverterButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="💱 Conversor de Moedas"
android:textSize="16sp"
android:textStyle="bold"
android:padding="16dp"
app:cornerRadius="12dp"
app:backgroundTint="@color/primary_color" />
<!-- Card de Conversão Principal -->
<androidx.cardview.widget.CardView
android:id="@+id/speedConversionCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/speedHeaderCard">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="24dp">
<!-- Valor de Entrada -->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="⚡ Velocidade"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-medium" />
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:hint="Digite a velocidade"
app:boxStrokeColor="@color/accent_color"
app:hintTextColor="@color/accent_color"
app:startIconDrawable="@android:drawable/ic_menu_edit"
app:startIconTint="@color/accent_color">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/speedAmountInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:textSize="20sp"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-light" />
</com.google.android.material.textfield.TextInputLayout>
<!-- Seleção de Unidades -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp">
<!-- Unidade de Origem -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginEnd="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🔄 De"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<Spinner
android:id="@+id/speedFromUnitSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
<!-- Botão de Troca -->
<ImageView
android:id="@+id/speedSwapButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_vertical"
android:layout_marginHorizontal="8dp"
android:src="@drawable/ic_swap"
android:background="@drawable/circle_background_speed"
android:padding="12dp"
android:contentDescription="Trocar unidades" />
<!-- Unidade de Destino -->
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical"
android:layout_marginStart="8dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🎯 Para"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<Spinner
android:id="@+id/speedToUnitSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:background="@drawable/spinner_background"
android:padding="12dp" />
</LinearLayout>
</LinearLayout>
<!-- Resultado -->
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
app:cardCornerRadius="12dp"
app:cardElevation="2dp"
app:cardBackgroundColor="@color/result_background">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="🏁 Resultado"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="@color/text_secondary"
android:fontFamily="sans-serif-medium" />
<TextView
android:id="@+id/speedResultText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Digite uma velocidade para converter"
android:textSize="24sp"
android:textStyle="bold"
android:textColor="@color/accent_color"
android:textAlignment="center"
android:fontFamily="sans-serif-light" />
<TextView
android:id="@+id/speedRateText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Selecione as unidades"
android:textSize="12sp"
android:textColor="@color/text_secondary"
android:textAlignment="center" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</androidx.cardview.widget.CardView>
<!-- Card de Exemplos -->
<androidx.cardview.widget.CardView
android:id="@+id/speedExamplesCard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
app:cardCornerRadius="16dp"
app:cardElevation="6dp"
app:cardBackgroundColor="@android:color/white"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/speedConversionCard">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="💡 Exemplos Comuns"
android:textSize="16sp"
android:textStyle="bold"
android:textColor="@color/text_primary"
android:fontFamily="sans-serif-medium" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="12dp"
android:text="🚗 Carro: 100 km/h = 27.78 m/s\n✈ Avião: 500 mph = 223.52 m/s\n🏃 Corredor: 10 m/s = 36 km/h\n🚢 Barco: 20 knot = 10.29 m/s\n🚀 Foguete: 1 mach = 343 m/s"
android:textSize="14sp"
android:textColor="@color/text_secondary"
android:lineSpacingExtra="4dp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
</ScrollView>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 982 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.6 KiB

View File

@@ -0,0 +1,7 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.Conversordemoedas2" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your dark theme here. -->
<!-- <item name="colorPrimary">@color/my_dark_primary</item> -->
</style>
</resources>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Cores principais -->
<color name="primary_color">#6366F1</color>
<color name="primary_dark">#4F46E5</color>
<color name="accent_color">#10B981</color>
<!-- Cores de texto -->
<color name="text_primary">#1F2937</color>
<color name="text_secondary">#6B7280</color>
<color name="text_light">#9CA3AF</color>
<!-- Cores de fundo -->
<color name="background_gradient">#F8FAFC</color>
<color name="result_background">#F3F4F6</color>
<color name="white_transparent">#80FFFFFF</color>
<!-- Cores de estado -->
<color name="success_color">#10B981</color>
<color name="error_color">#EF4444</color>
<color name="warning_color">#F59E0B</color>
<!-- Cores do sistema -->
<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
</resources>

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">conversordemoedas2</string>
</resources>

View File

@@ -0,0 +1,9 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Base.Theme.Conversordemoedas2" parent="Theme.Material3.DayNight.NoActionBar">
<!-- Customize your light theme here. -->
<!-- <item name="colorPrimary">@color/my_light_primary</item> -->
</style>
<style name="Theme.Conversordemoedas2" parent="Base.Theme.Conversordemoedas2" />
</resources>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample backup rules file; uncomment and customize as necessary.
See https://developer.android.com/guide/topics/data/autobackup
for details.
Note: This file is ignored for devices older than API 31
See https://developer.android.com/about/versions/12/backup-restore
-->
<full-backup-content>
<!--
<include domain="sharedpref" path="."/>
<exclude domain="sharedpref" path="device.xml"/>
-->
</full-backup-content>

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="utf-8"?><!--
Sample data extraction rules file; uncomment and customize as necessary.
See https://developer.android.com/about/versions/12/backup-restore#xml-changes
for details.
-->
<data-extraction-rules>
<cloud-backup>
<!-- TODO: Use <include> and <exclude> to control what is backed up.
<include .../>
<exclude .../>
-->
</cloud-backup>
<!--
<device-transfer>
<include .../>
<exclude .../>
</device-transfer>
-->
</data-extraction-rules>

View File

@@ -0,0 +1,17 @@
package com.example.conversordemoedas2;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}