編輯:開發入門
本節將實作一個簡易的有道辭典查詢範例。使用者可以在輸入框中輸入中文或英文單字,按下查詢按鈕後,程式會透過 WebView 載入有道辭典的行動版搜尋結果。


這個範例主要使用四個元件:EditText 用來輸入查詢內容,Button 用來觸發查詢或清空,WebView 用來顯示查詢結果,Toast 則用於提示使用者輸入不得為空。

<?XML version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText
android:id="@+id/myEditText1"
android:layout_width="200px"
android:layout_height="40px"
android:textSize="18sp"
android:layout_x="5px"
android:layout_y="32px" />
<Button
android:id="@+id/myButton01"
android:layout_width="60px"
android:layout_height="40px"
android:text="查詢"
android:layout_x="205px"
android:layout_y="35px" />
<Button
android:id="@+id/myButton02"
android:layout_width="50px"
android:layout_height="40px"
android:text="清空"
android:layout_x="270px"
android:layout_y="35px" />
<WebView
android:id="@+id/myWebView1"
android:layout_width="300px"
android:layout_height="330px"
android:layout_x="7px"
android:layout_y="90px"
android:background="@drawable/black"
android:focusable="false" />
</AbsoluteLayout>
package androidApplication.Instance;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class YouDao extends Activity {
private Button myButton01;
private Button myButton02;
private EditText mEditText1;
private WebView mWebView1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButton01 = (Button) findViewById(R.id.myButton01);
myButton02 = (Button) findViewById(R.id.myButton02);
mEditText1 = (EditText) findViewById(R.id.myEditText1);
mWebView1 = (WebView) findViewById(R.id.myWebView1);
myButton01.setOnClickListener(new Button.OnClickListener() {
public void onClick(View arg0) {
String strURI = mEditText1.getText().toString().trim();
if (strURI.length() == 0) {
Toast.makeText(YouDao.this, "查詢內容不能為空!", Toast.LENGTH_LONG).show();
} else {
String strURL = "https://dict.youdao.com/m/search?keyfrom=dict.mindex&q=" + strURI;
mWebView1.loadUrl(strURL);
}
}
});
myButton02.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
mEditText1.setText("");
}
});
}
}
這個範例展示了 Android 表單元件、事件監聽與 WebView 載入網頁的整合方式。若要實際發布,還需要處理網路權限、字元編碼與錯誤提示等細節。
動手打造 Android RSS 閱讀器(一):從 RSS 基礎到應用架構
開始之前 本教學介紹如何在 Android 平台之上處理 XML。若要照著本教學打造範例應用程式,你必須在開發電腦上安裝並運行 Android SDK。建議使用 Ecli
Facebook SDK for Android 入門(一):從 Graph API 動手做第一個社交應用
前言:把 Facebook 的社交能力搬進你的 App 想在自己的應用裡加入社交元素?Facebook 早就把這條路鋪好了。從行動端來看,Facebook Platfor
Android 學習筆記(一):平台歷史、架構與開發環境
Android 學習起點 這篇筆記整理 Android 入門時最常遇到的基礎概念,包含平台定義、歷史脈絡、系統架構、開發環境與第一個專案結構。對初學者而言,先建立整體輪廓
智慧交通之路(一):用 Google Maps 與 GTFS 打造你的通勤後盾
公共交通能紓解擁擠、削減由此而生的污染,順帶降低通勤者的壓力與花費。今天有為數眾多的網站與行動應用,正幫著世界各地的乘客、逛街的人和旅人變成「有道德的利己主義者」——把各