編輯:關於 Android 開發
上一篇用 LinearLayout 加基礎組件做了一個體育積分認證系統的界面。本篇往下走一步:熟悉 Button、RadioButton、EditText 的行為,學會掛事件監聽、彈出對話框、自定義對話框內容,並處理確定與取消按鈕的回饋。最後再補上兩個 Design Support Library 的實用組件。
setContentView() 把布局載入之後,才能用 findViewById() 取得其中的控件,所以第一步永遠是給控件一個 id。

定義 id 的語法與參照資源類似,寫成 @+id/名稱。同一個布局檔中不允许重複,不同控件也不行;但不同布局檔之間可以共用同一個 id。

findViewById() 帶一個參數,寫成 R.id.XXX。由於回傳型別是 View,必須強制轉型成實際的控件類別,例如 Button。
Toast 在開發與除錯時都會頻繁用到,測試階段也能搭配 logcat 一起看。
常用方法:cancel 關閉提示;getDuration 取得持續時間;getGravity 取得位置;makeText 產生標準 Toast;setView 設定自訂 View;getView 取得 View;setGravity 設定位置;getXOffset 與 getYOffset 取得位移量;setDuration 設定持續時間;setText 設定文字;show 顯示。
最基本的三參數寫法:

context 是上下文,寫「當前類名.this」即可;text 是顯示內容;duration 可選 Toast.LENGTH_SHORT 或 Toast.LENGTH_LONG。最後務必呼叫 show(),否則什麼都不會出現——這是最常見的初學者陷阱。
Toast 大致有三種形式:標準樣式、自訂位置、帶圖片。



import java.io.InputStream;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
@SuppressLint("ShowToast")
public class MainActivity extends Activity {
Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 初始化 Toast,主要作用是點擊時可以先立刻消除上一個 toast
toast = Toast.makeText(getApplicationContext(), "", 0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void Button1(View v) {
toast.cancel();
toast = Toast.makeText(getApplicationContext(), "系統默認的樣式", 1);
toast.show();
}
public void Button2(View v) {
// 清除上一個 toast,不會有顯示延遲,更加美觀
toast.cancel();
toast = Toast.makeText(getApplicationContext(), "設置Toast顯示的位置", 1);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
public void Button3(View v) {
toast.cancel();
toast = Toast.makeText(getApplicationContext(), "設置Toast顯示圖片和位置", 1);
toast.setGravity(Gravity.CENTER, 0, 0);
LinearLayout linearToast = (LinearLayout) toast.getView();
linearToast.setOrientation(LinearLayout.HORIZONTAL);
ImageView image = new ImageView(getApplicationContext());
// 為了美觀,將圖片縮小為原來的一半
InputStream is = this.getResources().openRawResource(R.drawable.ic_launcher);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
options.inSampleSize = 2; // width、height 設為原來的二分之一
Bitmap btp = BitmapFactory.decodeStream(is, null, options);
image.setImageBitmap(btp);
linearToast.addView(image, 0);
toast.show();
}
}
每次彈新的 Toast 前先 cancel 掉舊的,是為了避免上一個還沒消失就疊上新的,造成顯示延遲。
以 Button 為例。處理事件前,要先把相關控件都引入:想判斷用戶名是否為空,除了作為觸發主體的 Button,還得引入用戶名的輸入框。

在 button.setOnClickListener() 中完成處理。onClick 帶的 view 參數就是觸發該事件的控件參照:

EditText、Button、RadioGroup 各自的專用方法建議直接查 API 文檔,這裡不逐一列舉。
Android 最基礎的對話框是 AlertDialog。說它簡單,是因為布局由系統提供,你只要負責填內容:setTitle() 設標題、setIcon() 設圖示、setMessage() 設主要訊息。
AlertDialog.Builder 的常用方法:
setTitle 設標題;setIcon 設圖示;setMessage 設提示內容;setView 設自訂視圖;setItems 設列表;setMultiChoiceItems 設多選框;setNeutralButton 普通按鈕;setPositiveButton 添加「Yes」按鈕;setNegativeButton 添加「No」按鈕;create 建立對話框;show 顯示。
顯示一個 AlertDialog 的步驟:
(1)建立 AlertDialog.Builder 物件。
(2)呼叫上述方法逐項設定。
(3)若要處理取消按鈕:

(4)呼叫 create() 取得 AlertDialog,再呼叫它的 show() 顯示。
Google 在 2015 年 I/O 大會發布了更完整的 Material Design 規範與 Android Design Support Library,Snackbar 就是其中一員。它可以取代 Toast,除了使用者體驗更好,功能也更靈活。

make() 的三個參數分別是根布局、訊息、時長,這個方法是唯一必備的,其餘皆為選用,定義完呼叫 show() 即可顯示。
setAction() 讓右側按鈕可點擊並綁定事件,兩個參數是按鈕文字與點擊邏輯,寫法與 Button 相同。setActionTextColor() 設定按鈕文字顏色;setDuration() 設定顯示長度,單位為毫秒。要注意的是,一旦按下右側按鈕,Snackbar 會立刻消失。

踩坑記錄:在 API 19 的模擬器上按鈕顯示不出來,換成 API 22 就正常了,推測是版本支援的問題。
登錄註冊界面幾乎一定會用到 EditText,而我們通常還會額外放一個 TextView 當標籤,再靠 hint 提示輸入內容。TextInputLayout 把這些整合成一個組件。




它的兩個主要功能:
一、為 EditText 加上帶動畫的浮動標籤。做法是拿 EditText 的 hint 值當標籤內容,使用者一開始輸入,hint 就往上浮成標題,動畫過程中提示不會消失。
二、處理錯誤輸入。透過 setError(String message) 在 EditText 附近顯示錯誤訊息;setErrorEnabled(boolean) 則用來開關這個功能,傳入 false 就會移除已顯示的錯誤提示。
xml 布局:

一個 TextInputLayout 只能包一個 EditText。另外若在預覽中看不到效果,是因為缺少依賴,需要修改 build.gradle:


在 dependencies 中加入 design 庫並同步專案即可:

同步也可以在修改後直接點 Sync Now。
接著在 java 檔中引入 TextInputLayout,就能透過它取得內部 EditText 的內容:

顯示提示信息的寫法:

先 setErrorEnabled(true) 開啟,再 setError() 填入內容;想讓提示消失,把 setErrorEnabled(false) 即可。

要求:
(1)此界面為啟動後看到的第一個畫面。
(2)點擊登錄:用戶名為空則彈出「用戶名不能為空」;密碼為空則彈出「密碼不能為空」;若用戶名為 Android、密碼為 123456,彈出登錄成功對話框;否則彈出登錄失敗對話框。兩個對話框的確定與取消按鈕都各自彈出對應的 Toast。


(3)點擊註冊:依 RadioButton 的選項彈出對應的「XX 身份注冊功能尚未開啟」。
(4)切換 RadioButton 時,彈出「XX 身份被選中」。
在 setContentView() 之後用 findViewById() 取得各控件並宣告對應型別:

本次用到兩個事件監聽:Button 的 setOnClickListener() 與 RadioGroup 的 setOnCheckedChangeListener()。處理事件時,記得把該事件相關的控件都引入,再於監聽器中做判斷。

對話框的組裝流程如前述:建立 Builder、逐項設定、create()、show()。

進階部分先把 EditText 用 TextInputLayout 包起來並加上 hint:

修改 build.gradle 之後同步專案,再在 java 檔中宣告並取得 TextInputLayout:


在登錄監聽中依需求顯示或清除錯誤提示:

Snackbar 的部分,make() 為必備,其餘串接皆可選:

content_main.xml(基礎與進階部分共用)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorWhite"
android:orientation="vertical">
<TextView
android:id="@+id/SYSUTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="@string/sysu"
android:textSize="20sp"
android:textStyle="bold" />
<ImageView
android:id="@+id/sysuImage"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_marginBottom="20dp"
android:layout_marginTop="20dp"
android:contentDescription="@string/app_name"
android:src="@mipmap/sysu" />
<android.support.design.widget.TextInputLayout
android:id="@+id/more_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<EditText
android:id="@+id/editTextUsername"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/username2"
android:inputType="textPersonName" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="@+id/more_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<EditText
android:id="@+id/editTextPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:hint="@string/password2"
android:inputType="textPassword" />
</android.support.design.widget.TextInputLayout>
<RadioGroup
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioStu"
style="@style/radioButtonStyle"
android:checked="true"
android:text="@string/student" />
<RadioButton
android:id="@+id/radioTeacher"
style="@style/radioButtonStyle"
android:text="@string/teacher" />
<RadioButton
android:id="@+id/radioCorporation"
style="@style/radioButtonStyle"
android:text="@string/corporation" />
<RadioButton
android:id="@+id/radioManager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/manager"
android:textSize="@dimen/etWordSp" />
</RadioGroup>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:orientation="horizontal">
<Button
android:id="@+id/login"
style="@style/Button"
android:layout_marginRight="5dp"
android:text="@string/signIn" />
<Button
android:id="@+id/register"
style="@style/Button"
android:text="@string/register" />
</LinearLayout>
</LinearLayout>
MainActivity.java(基礎版)
package com.example.yanglh6.myapplication1;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup radio = null;
private RadioButton radioStu = null;
private RadioButton radioTeacher = null;
private RadioButton radioCorporation = null;
private RadioButton radioManager = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
Button buttonLogin = (Button) findViewById(R.id.login);
Button buttonRegister = (Button) findViewById(R.id.register);
final EditText editTextUsername = (EditText) findViewById(R.id.editTextUsername);
final EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
radio = (RadioGroup) findViewById(R.id.radio);
radioStu = (RadioButton) findViewById(R.id.radioStu);
radioTeacher = (RadioButton) findViewById(R.id.radioTeacher);
radioCorporation = (RadioButton) findViewById(R.id.radioCorporation);
radioManager = (RadioButton) findViewById(R.id.radioManager);
buttonLogin.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View view) {
if (TextUtils.isEmpty(editTextUsername.getText().toString())) {
Toast.makeText(MainActivity.this, "用戶名不能為空", Toast.LENGTH_SHORT).show();
} else if (TextUtils.isEmpty(editTextPassword.getText().toString())) {
Toast.makeText(MainActivity.this, "密碼不能為空", Toast.LENGTH_SHORT).show();
} else if (editTextUsername.getText().toString().equals("Android")
&& editTextPassword.getText().toString().equals("123456")) {
showDialog("登錄成功");
} else {
showDialog("登錄失敗");
}
}
});
radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == radioStu.getId()) {
Toast.makeText(MainActivity.this, "學生身份被選中", Toast.LENGTH_SHORT).show();
}
if (checkedId == radioTeacher.getId()) {
Toast.makeText(MainActivity.this, "教師身份被選中", Toast.LENGTH_SHORT).show();
}
if (checkedId == radioCorporation.getId()) {
Toast.makeText(MainActivity.this, "社團身份被選中", Toast.LENGTH_SHORT).show();
}
if (checkedId == radioManager.getId()) {
Toast.makeText(MainActivity.this, "管理者身份被選中", Toast.LENGTH_SHORT).show();
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio);
int checkedId = radioGroup.getCheckedRadioButtonId();
if (checkedId == R.id.radioStu) {
Toast.makeText(MainActivity.this, "學生身份注冊功能尚未開啟", Toast.LENGTH_SHORT).show();
} else if (checkedId == radioTeacher.getId()) {
Toast.makeText(MainActivity.this, "教師身份注冊功能尚未開啟", Toast.LENGTH_SHORT).show();
} else if (checkedId == radioCorporation.getId()) {
Toast.makeText(MainActivity.this, "社團身份注冊功能尚未開啟", Toast.LENGTH_SHORT).show();
} else if (checkedId == radioManager.getId()) {
Toast.makeText(MainActivity.this, "管理者身份注冊功能尚未開啟", Toast.LENGTH_SHORT).show();
}
}
});
}
/** 抽出重复的对话框代码,确定与取消各自弹出对应提示 */
private void showDialog(String message) {
new AlertDialog.Builder(MainActivity.this)
.setTitle("提示")
.setMessage(message)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "對話框\"確定\"按鈕被點擊",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, "對話框\"取消\"按鈕被點擊",
Toast.LENGTH_SHORT).show();
}
})
.create()
.show();
}
}
MainActivity.java(進階版:改用 TextInputLayout 與 Snackbar)
package com.example.yanglh6.myapplication1;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private RadioGroup radio = null;
private RadioButton radioStu = null;
private RadioButton radioTeacher = null;
private RadioButton radioCorporation = null;
private RadioButton radioManager = null;
private TextInputLayout usernameText;
private TextInputLayout passwordText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
usernameText = (TextInputLayout) findViewById(R.id.more_username);
passwordText = (TextInputLayout) findViewById(R.id.more_password);
Button buttonLogin = (Button) findViewById(R.id.login);
final Button buttonRegister = (Button) findViewById(R.id.register);
final EditText editTextUsername = (EditText) findViewById(R.id.editTextUsername);
final EditText editTextPassword = (EditText) findViewById(R.id.editTextPassword);
radio = (RadioGroup) findViewById(R.id.radio);
radioStu = (RadioButton) findViewById(R.id.radioStu);
radioTeacher = (RadioButton) findViewById(R.id.radioTeacher);
radioCorporation = (RadioButton) findViewById(R.id.radioCorporation);
radioManager = (RadioButton) findViewById(R.id.radioManager);
buttonLogin.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View view) {
// 用 TextInputLayout 取出内部 EditText 的内容
usernameText.getEditText().getText().toString().trim();
passwordText.getEditText().getText().toString().trim();
if (TextUtils.isEmpty(editTextUsername.getText().toString())) {
usernameText.setErrorEnabled(true);
usernameText.setError("用戶名不能為空");
return;
} else {
usernameText.setErrorEnabled(false);
}
if (TextUtils.isEmpty(editTextPassword.getText().toString())) {
passwordText.setErrorEnabled(true);
passwordText.setError("密碼不能為空");
return;
} else {
passwordText.setErrorEnabled(false);
}
if (editTextUsername.getText().toString().equals("Android")
&& editTextPassword.getText().toString().equals("123456")) {
snack("登錄成功");
} else {
snack("登錄失敗");
}
}
});
radio.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == radioStu.getId()) {
snack("學生身份被選中");
}
if (checkedId == radioTeacher.getId()) {
snack("教師身份被選中");
}
if (checkedId == radioCorporation.getId()) {
snack("社團身份被選中");
}
if (checkedId == radioManager.getId()) {
snack("管理者身份被選中");
}
}
});
buttonRegister.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio);
int checkedId = radioGroup.getCheckedRadioButtonId();
if (checkedId == R.id.radioStu) {
snack("學生身份注冊功能尚未開啟");
} else if (checkedId == radioTeacher.getId()) {
snack("教師身份注冊功能尚未開啟");
} else if (checkedId == radioCorporation.getId()) {
snack("社團身份注冊功能尚未開啟");
} else if (checkedId == radioManager.getId()) {
snack("管理者身份注冊功能尚未開啟");
}
}
});
}
/** 统一的 Snackbar 提示,带一个可点击的按钮 */
private void snack(String message) {
Snackbar.make(getWindow().getDecorView(), message, Snackbar.LENGTH_SHORT)
.setAction("按鈕", new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Snackbar的按鈕被點擊了",
Toast.LENGTH_SHORT).show();
}
})
.setDuration(5000)
.show();
}
}
Toast:三個參數 context、text、duration,最後一定要 show()。連續彈出時先 cancel 舊的,畫面才不會卡。
AlertDialog:它的建構子全是 protected,所以不能 new,必須透過 AlertDialog.Builder 的 create()。常用設定包含 setTitle、setIcon、setMessage、setView、setItems、setMultiChoiceItems、setNeutralButton、setPositiveButton、setNegativeButton,收尾是 create() 與 show()。
Snackbar:Design Support Library 的成員,在螢幕底部短暫顯示訊息,本質近似 Toast 但更靈活——可帶一個操作按鈕、可滑掉、且屬於 UI 的一部分,永遠疊在畫面最上層,同一時刻只會有一個顯示。make() 的第一個參數是一個 View,Snackbar 會沿著視圖樹往上找到第一個合適的容器作為寄主。setAction() 的簽名是 setAction(CharSequence text, View.OnClickListener listener),按鈕文字顏色預設取自主題的 colorAccent,可用 setActionTextColor(int color) 覆寫。
TextInputLayout:包住 EditText 後,hint 會在輸入開始時上浮成浮動標籤並附帶動畫,解決了「一打字提示就消失」的老問題;同時能用 setError() 在輸入框附近顯示錯誤訊息,並以 setErrorEnabled(false) 清除。使用它需要在 build.gradle 中加入 design 庫並同步專案。
實驗環境:Windows 10、Android Studio 2.2.1、模擬器 Nexus_5X、API 23。
Android 加固系列(五):從 JNI 層 Hook 系統 API 談起
Android 加固系列(五):從 JNI 層 Hook 系統 API 談起 【版權所有,轉載請註明出處】 加固與破解是一體兩面:唯有先理解攻擊者會從哪些環節下手,才知道
在 ListView 或 RecyclerView 中顯示可新增圖片的實作
在 ListView 或 RecyclerView 中顯示可新增圖片的實作這個效果看似是加上傳功能,實際上可以把整個區塊做成 ListView 或 RecyclerVie
Android 系統版本與 API Level 對照表
Android 系統版本與 API Level 對照表 在開發 Android 應用時,常需要確認最低支援版本與目標版本。下表整理 Android 系統版本與 API L
Android 編譯框架全流程:從源碼到 APK,以及 IDE 與 Gradle 要點
Android 應用編譯框架流程與 IDE、Gradle 概要 1. 背景 閱讀本文前,建議先看過《Android Studio 入門到精通》《Groovy 腳本基礎全