編輯:Android 開發實例
這是一個很適合入門者的小練習:EditText 裡預先帶入一段文字,按下 Show 鈕會彈出 AlertDialog 把輸入框內容顯示出來;按下 Clear 鈕則把輸入框清空。功能簡單,但把幾個最常見的元件都串起來了。
整個 Activity 用到了兩層 LinearLayout、兩個 Button、一個 TextView 與一個 EditText。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/text"
android:id="@+id/text" />
<LinearLayout android:id="@+id/linearlayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnShow"
android:id="@+id/btnShow" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btnClear"
android:id="@+id/btnClear" />
</LinearLayout>
</LinearLayout>
外層 LinearLayout 直向排列,把標題、輸入框與按鈕列依序疊上去;內層改成橫向並設定 gravity 為 center,讓兩個按鈕並排置中。
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class practice extends Activity {
Button btnShow;
Button btnClear;
EditText text;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShow = (Button) findViewById(R.id.btnShow);
btnClear = (Button) findViewById(R.id.btnClear);
text = (EditText) findViewById(R.id.text);
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AlertDialog.Builder(practice.this)
.setTitle("Infomation")
.setIcon(android.R.drawable.ic_dialog_dialer)
.setMessage(text.getText())
.show();
}
});
btnClear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
text.setText("");
}
});
}
}
AlertDialog 採用 Builder 模式串接設定,標題、圖示、訊息一路接上去,最後 show() 才真正把它推上前台。這裡的圖示直接借用了系統內建的 android.R.drawable 資源,省去找圖的麻煩。
setMessage() 接受的是 CharSequence,所以直接把 EditText 的 getText() 傳進去即可,不需要額外轉型。
Clear 鈕的做法更直觀:對同一個 EditText 呼叫 setText(""),內容就清空了。
Android JSON 解析實戰:用 JSONObject 抓取 API 資料
JSON 的全名是 JavaScript Object Notation,它把「人能讀、機器也好處理」這件事同時做到了。相較於標籤必須成對出現的 XML,JSON 沒有冗
Android 如何解析 JSON:從 API 回傳資料中取出欄位值
JSON 的全名是 JavaScript Object Notation,是一種與程式語言無關的資料交換格式。相較於 XML,它沒有冗長的標籤,結構清楚、體積更小,解析速
Android Matrix 圖像變換完全解析:平移、旋轉、鏡像、錯切與復合變換
線性代數裡學過矩陣,但真正把矩陣用來做圖像變換,往往是在實際項目中才想通。這篇把 android.graphics.Matrix 的理論與用法系統梳理一遍。 一、3×3
從 API 到畫面:Android 用 JSONObject 解析天氣資料的整條路
行動 App 的資料大多不是自己產生的,而是從伺服器抓回來的。而這些年最主流的傳輸格式,莫過於 JSON——它比 XML 短、比 XML 好讀,解析器幾乎每個語言都內建。