You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
5MI/DropdownMenu.java

56 lines
2.5 KiB

/*
* 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.
*/
// 定义一个名为DropdownMenu的公开类
public class DropdownMenu {
// 声明一个Button类型的私有成员变量mButton用于存储下拉按钮
private Button mButton;
// 声明一个PopupMenu类型的私有成员变量mPopupMenu用于存储弹出的菜单
private PopupMenu mPopupMenu;
// 声明一个Menu类型的私有成员变量mMenu用于存储菜单项
private Menu mMenu;
// 构造方法初始化DropdownMenu对象
public DropdownMenu(Context context, Button button, int menuId) {
mButton = button; // 将传入的Button对象赋值给mButton
mButton.setBackgroundResource(R.drawable.dropdown_icon); // 设置按钮的背景资源为dropdown_icon
mPopupMenu = new PopupMenu(context, mButton); // 创建一个新的PopupMenu对象并将其与mButton绑定
mMenu = mPopupMenu.getMenu(); // 获取PopupMenu中的Menu对象
mPopupMenu.getMenuInflater().inflate(menuId, mMenu); // 使用menuId指定的XML布局文件来填充Menu对象
mButton.setOnClickListener(new OnClickListener() { // 为mButton设置点击监听器
public void onClick(View v) {
mPopupMenu.show(); // 当按钮被点击时显示PopupMenu
}
});
}
// 设置PopupMenu的菜单项点击监听器
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
if (mPopupMenu != null) {
mPopupMenu.setOnMenuItemClickListener(listener); // 为PopupMenu设置菜单项点击监听器
}
}
// 根据ID查找菜单项
public MenuItem findItem(int id) {
return mMenu.findItem(id); // 在Menu对象中查找具有指定ID的菜单项并返回它
}
// 设置按钮的标题
public void setTitle(CharSequence title) {
mButton.setText(title); // 将传入的CharSequence对象设置为按钮的标题
}
}