編輯:關於 Android 程式設計
系統預設的按鈕外觀很難客製,想做出圓角效果,最乾淨的做法是用一個 shape drawable 定義好外觀,再掛到按鈕的背景上。整個過程不需要寫一行 Java。
在 res/drawable/ 下新增 shape.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<!-- 填充顏色 -->
<solid android:color="#FFFFFF" />
<!-- 四個角設為弧形,radius 為弧的半径 -->
<corners android:radius="5dip" />
<!-- 文字與按鈕邊界的間距 -->
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp" />
</shape>
shape 的常用子元素:
<solid>:純色填充。<gradient>:漸層填充,可指定起始色、結束色與角度。<stroke>:邊框,可設定 width、color、dashWidth(虛線)。<corners>:圓角。<padding>:內距。
<?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" />
<Button
android:id="@+id/roundButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" 圓角按鈕 "
android:background="@drawable/shape" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, RoundButtonDemoActivity!</string>
<string name="app_name">RoundButtonDemo</string>
</resources>
package com.android.RoundButtonDemo.activity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class RoundButtonDemoActivity extends Activity {
Button roundButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
roundButton = (Button) findViewById(R.id.roundButton);
// 以匿名類別註冊點擊事件
roundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(RoundButtonDemoActivity.this,
"你點擊了圓角按鈕", Toast.LENGTH_LONG).show();
}
});
}
}
靜態的 shape 不會回應觸控。若想要「按下去變色」,再用一層 selector 把兩個 shape 包起來:
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_pressed" />
<item android:drawable="@drawable/shape" />
</selector>
然後把按鈕的 android:background 指向這個 selector 即可。
新版 Android 更推薦使用 MaterialButton 並透過 app:cornerRadius 屬性設定圓角,能自動獲得漣漪效果、狀態色切換與無障礙支援,不必自己維護多份 drawable。
Android 錄音與播放功能的簡單實例
錄音與播放是 Android 多媒體開發中的基礎功能。透過 MediaRecorder 可以錄製音頻,透過 MediaPlayer 則可以播放錄音檔案。兩者搭配,就能完成
Android Handler 基本用法:子線程更新 UI 的標準解法
Android 有個硬性規則:UI 只能在主線程(UI 線程)操作。但耗時任務又必須放在子線程執行,兩者之間的橋樑就是 Handler。本文整理 Handler 的核心概
高仿索尼滾動相冊:Android 順滑滾動相冊效果實現
索尼手機銷量雖普通,但有些設計確實出色,其相冊的雙指縮放與桌面滾動相冊小部件都相當炫酷。網上少見有人實作後者,於是本文分享一個高仿版本。效果圖:主要手勢操作1. 上/下滿
Android ClassLoader 熱修復技術流派縱覽
大約在 2015 年 10 月底,QQ 空間發表了一篇名為《安卓 App 熱補丁動態修復技術介紹》的文章。文中提到,要讓 Class 能夠進行熱修復,其中一個關鍵條件就是