自定义菜单,主要的思路就是利用PopupWindow来模仿菜单的效果。效果图如下:
具体代码如下:
1、关键代码
ArrayAdapter<String> listAdatper = new ArrayAdapter<String>(getApplicationContext(),
R.layout.item_menu_list,
R.id.menuText, new String[]{"删除","设置"});
// 加载popupWindow的布局文件
View popupWindowView = LayoutInflater.from(getApplicationContext())
.inflate(R.layout.view_popwindow, null);
final ListView menuList = (ListView)popupWindowView.findViewById(R.id.menuList);
menuList.setAdapter(listAdatper);
menuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
// 删除
Log.e(TAG, "000000000");
break;
case 1:
// 设置
Log.e(TAG, "111111111");
break;
default:
Log.e(TAG, "default");
break;
}
}
});
final PopupWindow popupWindow = new PopupWindow(popupWindowView, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mainMenu.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View v) {
// 如果不在弹出之前加上这条语句,ListView的item将无法点击
popupWindow.setFocusable(true);
// 防止弹出菜单获取焦点之后,点击activity的其他组件没有响应
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAsDropDown(mainMenu);
}
});
2、xml文件代码
1)item_menu_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/menuText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:textSize="18sp"/>
</LinearLayout>
2)view_popwindow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LinearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@drawable/menu_dropdown_panel_holo_dark">
<ListView
android:id="@+id/menuList"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:divider="#474747"
android:dividerHeight="1dp"/>
</LinearLayout>