修改android4.4图库系列二——自定义菜单

本文介绍如何通过PopupWindow创建自定义菜单效果,并提供详细代码实现,包括关键代码片段和必要的XML布局文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

自定义菜单,主要的思路就是利用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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值