編輯:關於 Android 程式設計
這一篇把三個「選擇類」控件放在一起講:多選的 CheckBox、單選的 RadioButton,以及下拉列表 Spinner。它們看起來簡單,但真正做出好看的交互,關鍵往往在選擇器與著色這兩個細節上。
CheckBox 直接繼承自 Button,所以 Button 的屬性它基本都能用。
選擇器裡有兩個狀態值得記住:state_checked 表示「已經被選中」,state_checkable 表示「可以被選中」。
先準備兩個 shape 作為背景:
<!-- cb_bg.xml:未選中 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<stroke android:color="#000" android:width="2dp" />
<size android:width="20dp" android:height="20dp" />
</shape>
<!-- cb_bg_1.xml:已選中,填紅色 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<stroke android:color="#000" android:width="2dp" />
<solid android:color="#f00" />
<size android:width="20dp" android:height="20dp" />
</shape>
再用 selector 把兩者串起來:
<!-- cb_sel.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/cb_bg_1" android:state_checked="true" />
<item android:drawable="@drawable/cb_bg" />
</selector>
最後掛到控件上,注意是 android:button 而不是背景:
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:button="@drawable/cb_sel" />

做一個類似點贊的小互動:選中變綠,未選中保持原樣。顏色同樣用 selector 表達:
<!-- cb_color_sel.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:color="#0f0" android:state_checked="true" />
<item android:color="#0000" />
</selector>
布局上有兩個要點:把原生 button 置空(@null),並用 drawableTop 把圖示放到文字上方。
<CheckBox
android:id="@+id/main_cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:button="@null"
android:checked="true"
android:drawableTop="@mipmap/ic_launcher"
android:text="復選框" />
接下來麻煩一點:給 drawableTop 著色。理論上 android:drawableTint 可以搞定,但那是 API 23 才有的屬性,在低版本上基本用不了,所以要走兼容方案。
CheckBox checkBox = (CheckBox) findViewById(R.id.main_cb);
// checkBox.setCompoundDrawableTintList(); API 23 之後才可用
// 取得控件四周的 drawable,陣列順序是「左上右下」
Drawable[] drawables = checkBox.getCompoundDrawables();
Drawable top = drawables[1];
// 用兼容包著色:1. 目標 drawable 2. 顏色狀態列表
ColorStateList list = getResources().getColorStateList(R.color.cb_color_sel);
DrawableCompat.setTintList(top, list);
DrawableCompat.setTintMode(top, PorterDuff.Mode.SRC_ATOP);
checkBox.setOnCheckedChangeListener(this);
checkBox.setText("+" + count);
事件回調裡根據是否選中來更新文字:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
buttonView.setText("+" + (count + (isChecked ? 1 : 0)));
}

兩個容易踩的點:
~Compat 的類,基本都是 support 包裡的兼容實現。getCompoundDrawables() 回傳的是控件上下左右四個位置的 drawable,索引 0 到 3,順序固定為「左上右下」。用 RadioButton 拼一個類似微信底部導航的樣子。注意 RadioGroup 繼承自 LinearLayout,裡面只能放 RadioButton;而 RadioButton 繼承自 CompoundButton。
<RadioGroup
android:id="@+id/main_group"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<RadioButton
android:id="@+id/rb_0"
android:drawableTop="@android:drawable/ic_menu_send"
android:text="發送" />
<RadioButton
android:id="@+id/rb_1"
android:drawableTop="@android:drawable/ic_menu_camera"
android:text="相機" />
<RadioButton
android:id="@+id/rb_2"
android:drawableTop="@android:drawable/ic_menu_call"
android:text="電話" />
<RadioButton
android:id="@+id/rb_3"
android:drawableTop="@android:drawable/ic_menu_agenda"
android:text="日程" />
</RadioGroup>
樣式抽成 style,避免每個按鈕都重複寫一遍(被註釋掉的兩行是 API 23 才支援的寫法):
<style name="radioStyle">
<item name="android:layout_width">0dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_weight">1</item>
<item name="android:gravity">center</item>
<item name="android:button">@null</item>
<item name="android:textColor">@color/cb_color_sel</item>
<!-- <item name="android:drawableTint">@color/cb_color_sel</item> -->
<!-- <item name="android:drawableTintMode">src_atop</item> -->
</style>
著色部分和 CheckBox 思路一致,只是要遍歷整個分組:
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.main_group);
for (int i = 0; i < radioGroup.getChildCount(); i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
Drawable drawable = button.getCompoundDrawables()[1];
DrawableCompat.setTintList(drawable, list);
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_ATOP);
}

小圓點數量不固定,所以要在代碼裡動態添加。先準備兩個 oval shape 和一個 selector:
<!-- nav_bg.xml:未選中,深灰 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="oval">
<size android:width="10dp" android:height="10dp" />
<solid android:color="#444" />
</shape>
<!-- nav_bg_1.xml:已選中,淺灰 -->
<shape xmlns:android="https://schemas.android.com/apk/res/android" android:shape="oval">
<size android:width="10dp" android:height="10dp" />
<solid android:color="#ccc" />
</shape>
<!-- nav_sel.xml -->
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/nav_bg_1" android:state_checked="true" />
<item android:drawable="@drawable/nav_bg" />
</selector>
布局裡只留一個空的 RadioGroup:
<RadioGroup
android:id="@+id/main_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="horizontal">
</RadioGroup>
然後用 LayoutInflater 反覆填充子項:
LayoutInflater inflater = LayoutInflater.from(this);
navigation = (RadioGroup) findViewById(R.id.main_navigation);
for (int i = 0; i < 10; i++) {
// 第二個參數不能傳 null;第三個參數決定是否立刻掛上父容器
// 傳 true 會回傳父控件,傳 false 才回傳 View 本身
RadioButton radioButton = inflater.inflate(R.layout.radio_child, navigation, false);
radioButton.setId(i);
navigation.addView(radioButton);
}
navigation.check(0);
監聽裡讓選中項循環前進,就能驅動輪播:
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int i = navigation.getCheckedRadioButtonId();
i++;
if (i >= navigation.getChildCount()) {
i = 0;
}
navigation.check(i);
}

先說個背景知識:適配器視圖 AdapterView 繼承自 ViewGroup,它負責把數據源按一定規則鋪到屏幕上。
<!-- strings.xml -->
<string-array name="test_data">
<item>Test 01</item>
<item>Test 02</item>
<item>Test 03</item>
<item>Test 04</item>
<item>Test 05</item>
</string-array>
<!-- 布局,popupBackground 控制彈出層背景色 -->
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:entries="@array/test_data"
android:popupBackground="#fff" />

這種方式限制太多,實戰中用得不多。牢記一個原則:View 永遠不直接操作數據源,數據源只能通過控制器(Adapter)來操作。
三個 Spinner 並排,每個各配一個 Adapter,通過監聽上層的選中項去刷新下層數據。
public class MainActivity extends AppCompatActivity
implements AdapterView.OnItemSelectedListener {
private ArrayAdapter<String> adapter;
private ArrayAdapter<String> adapter_1;
private ArrayAdapter<String> adapter_2;
private static final String[] PROVINCES = {"北京", "河北", "山東"};
private static final String[][] CITIES = {
{"北京"}, {"石家莊", "邯鄲", "衡水", "張家口"}, {"濟南", "泰安", "青島", "日照"}};
private static final String[][][] AREAS = {
{{{"海澱", "昌平", "朝陽", "東城", "西城"}}},
{{{"A", "B"}, {"C", "D"}, {}, {}}},
{{}, {}, {}, {}}};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.main_spinner);
spinner_1 = (Spinner) findViewById(R.id.main_spinner_1);
spinner_2 = (Spinner) findViewById(R.id.main_spinner_2);
// 建立 View 需要 Context;這裡三個 Adapter 各自綁定一份數據源
adapter = new ArrayAdapter<>(this, R.layout.spinner_child, R.id.item_text,
new ArrayList<>(Arrays.asList(PROVINCES)));
adapter_1 = new ArrayAdapter<>(this, R.layout.spinner_child, R.id.item_text,
new ArrayList<>(Arrays.asList(CITIES[0])));
adapter_2 = new ArrayAdapter<>(this, R.layout.spinner_child, R.id.item_text,
new ArrayList<>(Arrays.asList(AREAS[0][0])));
spinner.setAdapter(adapter);
spinner_1.setAdapter(adapter_1);
spinner_2.setAdapter(adapter_2);
// Spinner 故意不提供 setOnItemClickListener,強行調用會直接拋異常
spinner.setOnItemSelectedListener(this);
spinner_1.setOnItemSelectedListener(this);
spinner_2.setOnItemSelectedListener(this);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()) {
case R.id.main_spinner:
adapter_1.clear();
adapter_1.addAll(CITIES[position]);
adapter_2.clear();
adapter_2.addAll(AREAS[spinner.getSelectedItemPosition()][position]);
break;
case R.id.main_spinner_1:
adapter_2.clear();
adapter_2.addAll(AREAS[spinner.getSelectedItemPosition()][position]);
// 沒有下級數據時乾脆隱藏第三列
spinner_2.setVisibility(adapter_2.isEmpty() ? View.INVISIBLE : View.VISIBLE);
break;
case R.id.main_spinner_2:
StringBuilder builder = new StringBuilder();
builder.append(spinner.getSelectedItem()).append(":")
.append(spinner_1.getSelectedItem()).append(":")
.append(spinner_2.getSelectedItem());
Toast.makeText(MainActivity.this, builder.toString(), Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
}

三個控件串起來看,共同點是「狀態驅動外觀」:CheckBox 與 RadioButton 靠 selector 切換背景與著色,Spinner 靠 Adapter 切換數據。把選擇器和兼容著色這兩件事弄熟,這類需求基本都能應付。
Android NDK 使用入門:從命令行編譯到 Android Studio 集成
今天我們來簡單說說 Android NDK 的使用方法。眾所周知,so 文件在 Android 開發過程中扮演著舉足輕重的角色,無論是與底層設備打交道,還是 Androi
三星 S4(i9500)刷入魅族 Flyme ROM 圖解教學
魅族 Flyme OS for 三星 i9500 經過數輪內測後終於釋出,目前僅支援三星 i9500 這一款型號。想省事的人可以直接用刷機精靈一鍵刷入;以下提供手動做法,
Android 實用圖文教學:程式碼混淆、第三方加固與多渠道分發
本文以圖文並茂的方式,帶你走完 Android 應用發布前的關鍵流程:程式碼混淆、第三方平台加固加密與多渠道分發。 第一步:程式碼混淆(留意引入的第三方 jar) 在新版
Android 四大基本佈局詳解:LinearLayout、RelativeLayout、FrameLayout、TableLayout
佈局是 UI 開發的地基。本文用可運行的小例子,把四種最常見的佈局容器一次講清楚。 一、LinearLayout:線性佈局 LinearLayout 最關鍵的屬性是 a