當程式開啟 , 畫面要求使用者輸入匯率與台幣金額 , 輸入完成按下按鈕 , 即可在下方顯示計算結果 , 當下次開啟程式時會顯示上一次所輸入的匯率 , 這題使用 SharedPreferences類別將我們所輸入的資料儲存在 /data/data/package name/SharedPreferences_Name 下 , 記得在onPause()儲存 , onResume()取出就可以了 , 以下是程式碼。
package COM.TQC.GDD02; import java.text.DecimalFormat; import java.text.NumberFormat; import android.app.Activity; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class GDD02 extends Activity { public static final String PREF_ExchangeRate = "Exchange_Rate" ; private Button calcbutton ; private EditText fieldExchangeRate ; private EditText fieldNTD ; private TextView tv; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); fieldExchangeRate = (EditText) this.findViewById(R.id.editText1); fieldNTD = (EditText) this.findViewById(R.id.editText2); tv = (TextView) this.findViewById(R.id.usd_result); calcbutton = (Button) this.findViewById(R.id.calc_btn); calcbutton.setOnClickListener(BOnClickListener); } public Button.OnClickListener BOnClickListener = new Button.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub try { double NTD= Double.parseDouble(fieldNTD.getText().toString()); double ExchangeRate= Double.parseDouble(fieldExchangeRate.getText().toString()); NumberFormat NF = new DecimalFormat(".##"); tv.setText(getText(R.string.usd_result) + NF.format(NTD / ExchangeRate)); }catch(Exception e) { e.printStackTrace(); } } }; public void onResume() { super.onResume(); SharedPreferences settings = getSharedPreferences(PREF_ExchangeRate, 0); fieldExchangeRate.setText(settings.getString(PREF_ExchangeRate, "")); } public void onPause() { super.onPause(); SharedPreferences settings = getSharedPreferences(PREF_ExchangeRate, 0); settings.edit().putString(PREF_ExchangeRate, fieldExchangeRate.getText().toString()).commit(); } }
接下來是 main.xml檔
P.S. 題目中所要求的Variable和Method皆會保留 , 也會根據題目所要求的流程去實作 , 縱使題目要求繞遠路....
沒有留言:
張貼留言