1、設計好xml畫面
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Spinner android:id="@+id/choise" android:layout_width="match_parent" android:layout_height="wrap_content" /> <EditText android:id="@+id/input" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="number" > <requestFocus /> </EditText> <Button android:id="@+id/check" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="轉換" android:onClick="btnClick" /> </LinearLayout> |
3、撰寫Activity程式碼
package com.android.final_test_15_6_9; import com.android.final_test_14_6_9.R; import android.app.Activity; import android.app.AlertDialog; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.SpinnerAdapter; public class Final_Test_15_6_9Activity extends Activity{ /** Called when the activity is first created. */ private Spinner spChoise; private static String[] sChoise; private EditText edInput; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);//接收xml畫面 sChoise = getResources().getStringArray(R.array.sCheck);//Spinner元件sChoise接收在string.xml內的陣列文字 spChoise = (Spinner) findViewById(R.id.choise); edInput = (EditText) findViewById(R.id.input); ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,sChoise);//宣告ArrayAdapter承接字串陣列 spChoise.setAdapter(a);//設定Adapter至Spinner } public void btnClick(View view){ AlertDialog.Builder builder = new AlertDialog.Builder(this);//對話方塊 builder.setTitle("轉換結果"); double dInput = Double.valueOf(edInput.getText().toString()); if (spChoise.getSelectedItem().equals(sChoise[0])) builder.setMessage(String.format("華氏%.2f度,轉為攝氏%.2f度", dInput,(dInput-32.0)*5.0/9.0)); else if (spChoise.getSelectedItem().equals(sChoise[1])) builder.setMessage(String.format("攝氏%.2f度,轉為華氏%.2f度", dInput,dInput*(9.0/5.0)+32.0)); builder.setPositiveButton("確定", null); builder.show(); } } |
留言
張貼留言