編輯:關於 Android 程式設計
本文示範如何點擊頂部工具欄上的按鈕,向下彈出一份下拉式菜單。工具欄分成左、中、右三個入口,各自對應一份獨立的菜單清單。






activity_main.xml 以 RelativeLayout 為骨架,頂部橫幅 rl_topbar 內放三個 TextView:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#897D13"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/rl_topbar"
android:layout_width="match_parent"
android:layout_height="40dip"
android:background="#BF7F40"
android:gravity="center_vertical">
<TextView
android:id="@+id/tv_left"
android:layout_width="70dip"
android:layout_height="30dip"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:background="@drawable/btn_selector_pop"
android:clickable="true"
android:gravity="center"
android:text="left"
android:textColor="@android:color/white"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_middle"
android:layout_width="70dip"
android:layout_height="30dip"
android:layout_centerHorizontal="true"
android:background="@drawable/btn_selector_pop"
android:clickable="true"
android:gravity="center"
android:text="middle"
android:textColor="@android:color/white"
android:textSize="16sp" />
<TextView
android:id="@+id/tv_right"
android:layout_width="70dip"
android:layout_height="30dip"
android:layout_alignParentRight="true"
android:layout_marginRight="10dip"
android:background="@drawable/btn_selector_pop"
android:clickable="true"
android:gravity="center"
android:text="right"
android:textColor="@android:color/white"
android:textSize="16sp" />
</RelativeLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Drop-down"
android:textColor="@android:color/white"
android:textSize="20sp" />
</RelativeLayout>
三個入口的做法幾乎一致,因此把重複的部分收斂成一個共用方法,可讀性會好很多:
public class MainActivity extends Activity {
private RelativeLayout rlTopBar;
private TextView tvLeft, tvMiddle, tvRight;
private PopupWindow popLeft, popMiddle, popRight;
private final List<Map<String, String>> listLeft = new ArrayList<>();
private final List<Map<String, String>> listMiddle = new ArrayList<>();
private final List<Map<String, String>> listRight = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rlTopBar = (RelativeLayout) findViewById(R.id.rl_topbar);
tvLeft = (TextView) findViewById(R.id.tv_left);
tvMiddle = (TextView) findViewById(R.id.tv_middle);
tvRight = (TextView) findViewById(R.id.tv_right);
buildData(listLeft, "left");
buildData(listMiddle, "mid");
buildData(listRight, "right");
tvLeft.setOnClickListener(myListener);
tvMiddle.setOnClickListener(myListener);
tvRight.setOnClickListener(myListener);
}
/** 產生 9 筆示範資料 */
private void buildData(List<Map<String, String>> target, String prefix) {
for (int i = 1; i < 10; i++) {
Map<String, String> map = new HashMap<>();
map.put("item", prefix + i);
target.add(map);
}
}
/** 建立並顯示下拉視窗 */
private void showDropDown(TextView anchor, PopupWindow popup,
List<Map<String, String>> data) {
View content = getLayoutInflater().inflate(R.layout.pop_menulist, null);
ListView listView = (ListView) content.findViewById(R.id.menulist);
listView.setAdapter(new SimpleAdapter(this, data,
R.layout.pop_menuitem,
new String[]{"item"}, new int[]{R.id.menuitem}));
final PopupWindow window = new PopupWindow(
content, anchor.getWidth(), LayoutParams.WRAP_CONTENT);
window.setBackgroundDrawable(new ColorDrawable(0x00000000));
window.setAnimationStyle(R.style.PopupAnimation);
window.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
window.setTouchable(true);
window.setOutsideTouchable(true);
window.setFocusable(true);
window.update();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
anchor.setText(((TextView) view.findViewById(R.id.menuitem))
.getText().toString());
if (window.isShowing()) {
window.dismiss();
}
}
});
// 讓菜單緊貼工具欄下緣
int topBarHeight = rlTopBar.getBottom();
window.showAsDropDown(anchor, 0,
(topBarHeight - anchor.getHeight()) / 2);
window.setTouchInterceptor(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
window.dismiss();
return true;
}
return false;
}
});
}
private final View.OnClickListener myListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_left:
toggle(popLeft, tvLeft, listLeft);
break;
case R.id.tv_middle:
toggle(popMiddle, tvMiddle, listMiddle);
break;
case R.id.tv_right:
toggle(popRight, tvRight, listRight);
break;
default:
break;
}
}
};
/** 已展開則收合,未展開則彈出 */
private void toggle(PopupWindow popup, TextView anchor,
List<Map<String, String>> data) {
if (popup != null && popup.isShowing()) {
popup.dismiss();
return;
}
PopupWindow created = createAnchorWindow(anchor, data);
if (anchor == tvLeft) popLeft = created;
else if (anchor == tvMiddle) popMiddle = created;
else popRight = created;
}
private PopupWindow createAnchorWindow(TextView anchor,
List<Map<String, String>> data) {
View content = getLayoutInflater().inflate(R.layout.pop_menulist, null);
ListView listView = (ListView) content.findViewById(R.id.menulist);
listView.setAdapter(new SimpleAdapter(this, data,
R.layout.pop_menuitem,
new String[]{"item"}, new int[]{R.id.menuitem}));
final PopupWindow window = new PopupWindow(
content, anchor.getWidth(), LayoutParams.WRAP_CONTENT);
window.setBackgroundDrawable(new ColorDrawable(0x00000000));
window.setAnimationStyle(R.style.PopupAnimation);
window.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
window.setTouchable(true);
window.setOutsideTouchable(true);
window.setFocusable(true);
window.update();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
anchor.setText(((TextView) view.findViewById(R.id.menuitem))
.getText().toString());
if (window.isShowing()) window.dismiss();
}
});
int topBarHeight = rlTopBar.getBottom();
window.showAsDropDown(anchor, 0,
(topBarHeight - anchor.getHeight()) / 2);
return window;
}
}
原理並不複雜:點擊工具欄上的 TextView 後彈出一個 PopupWindow,視窗內容是一個 ListView,逐行呈現菜單項;選中後把文字回寫到工具欄並關閉視窗。
pop_menulist.xml 只承載一個 ListView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/shape_bg_pop"
android:orientation="vertical">
<ListView
android:id="@+id/menulist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#696969"
android:dividerHeight="1.0dip"
android:padding="2dip"
android:scrollbars="none" />
</LinearLayout>
pop_menuitem.xml 則是單一 TextView 構成的一列:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_list_item_pop"
android:orientation="horizontal">
<TextView
android:id="@+id/menuitem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textColor="@android:color/white"
android:textSize="16sp" />
</LinearLayout>
setFocusable(true) 讓視窗取得焦點,才能攔截到外部觸摸事件。showAsDropDown() 的第二、三個參數是相對錨點的偏移量,扣掉半個高度差可讓菜單垂直對齊工具欄底緣。其餘的 shape、selector 等資源檔屬於樣式裝飾,可依專案設計稿自行調整。
Android 非同步任務 AsyncTask 完整指南
AsyncTask 是 Android 早期為了解決「耗時操作不能跑在主執行緒」而提供的便捷方案。它讓背景運算與 UI 更新能用同一個類別寫完,不必自己管理執行緒與 Ha
Android 學習筆記:在運行時動態添加 Fragment
Fragment 的一大優勢在於可以靈活組合界面。除了靜態添加到布局中,Fragment 還可以在運行時動態添加,這使得界面適配與模塊化設計更加靈活。動態添加的基本流程首
【首發】在 Android Studio 中輕鬆搭建 JavaCV 開發環境
最近參加一個比賽需要用到人臉識別,但賽方限制了不能調用第三方雲服務 API,於是我想到了用 JavaCV 來自己實現。可搜索下來,絕大多數教程都是在 Eclipse 裡搭
Android 自定義 View:粒子雨動畫的抽象設計與多線程繪製
粒子雨效果拆解 粒子雨動畫通常由大量細小線條或粒子持續移動構成。若要讓程式碼易於擴充,可以先把共同流程抽象成基礎 View,再讓具體效果繼承並實作繪製、初始化與移動方法。