|
|
|
@ -0,0 +1,63 @@
|
|
|
|
|
/*
|
|
|
|
|
* Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
|
|
|
|
|
*
|
|
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
|
* you may not use this file except in compliance with the License.
|
|
|
|
|
* You may obtain a copy of the License at
|
|
|
|
|
*
|
|
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
|
*
|
|
|
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
|
* See the License for the specific language governing permissions and
|
|
|
|
|
* limitations under the License.
|
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
|
package net.micode.notes.ui; // 定义类所在的包路径
|
|
|
|
|
|
|
|
|
|
import android.content.Context; // 引入Context类,用于访问应用程序的上下文
|
|
|
|
|
import android.view.Menu; // 引入Menu类,用于操作菜单
|
|
|
|
|
import android.view.MenuItem; // 引入MenuItem类,用于菜单项的处理
|
|
|
|
|
import android.view.View; // 引入View类,用于视图的操作
|
|
|
|
|
import android.view.View.OnClickListener; // 引入OnClickListener接口,用于处理点击事件
|
|
|
|
|
import android.widget.Button; // 引入Button类,用于显示按钮
|
|
|
|
|
import android.widget.PopupMenu; // 引入PopupMenu类,用于显示弹出菜单
|
|
|
|
|
import android.widget.PopupMenu.OnMenuItemClickListener; // 引入PopupMenu的菜单项点击监听器
|
|
|
|
|
|
|
|
|
|
public class DropdownMenu {
|
|
|
|
|
private Button mButton; // 用于显示的按钮,点击后弹出菜单
|
|
|
|
|
private PopupMenu mPopupMenu; // 弹出菜单的实例
|
|
|
|
|
private Menu mMenu; // 菜单项的集合
|
|
|
|
|
|
|
|
|
|
// 构造函数,初始化DropdownMenu,设置按钮及其弹出菜单
|
|
|
|
|
public DropdownMenu(Context context, Button button, int menuId) {
|
|
|
|
|
mButton = button; // 获取传入的按钮对象
|
|
|
|
|
mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮的背景图标为下拉菜单图标
|
|
|
|
|
mPopupMenu = new PopupMenu(context, mButton); // 初始化PopupMenu,指定按钮作为弹出菜单的锚点
|
|
|
|
|
mMenu = mPopupMenu.getMenu(); // 获取PopupMenu中的Menu对象
|
|
|
|
|
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); // 使用传入的menuId加载菜单资源
|
|
|
|
|
mButton.setOnClickListener(new OnClickListener() { // 为按钮设置点击事件监听器
|
|
|
|
|
public void onClick(View v) {
|
|
|
|
|
mPopupMenu.show(); // 当按钮被点击时,显示弹出菜单
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 设置菜单项点击事件监听器
|
|
|
|
|
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
|
|
|
|
|
if (mPopupMenu != null) {
|
|
|
|
|
mPopupMenu.setOnMenuItemClickListener(listener); // 设置PopupMenu的菜单项点击监听器
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 根据菜单项的ID查找菜单项
|
|
|
|
|
public MenuItem findItem(int id) {
|
|
|
|
|
return mMenu.findItem(id); // 在菜单中查找具有指定ID的菜单项
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// 设置按钮的文本
|
|
|
|
|
public void setTitle(CharSequence title) {
|
|
|
|
|
mButton.setText(title); // 设置按钮的文本为传入的title
|
|
|
|
|
}
|
|
|
|
|
}
|