|
|
|
|
|
|
|
|
|
|
|
|
|
|
/*这段代码展示了如何在 Android 应用程序中实现一个带有弹出菜单的下拉按钮。
|
|
|
|
|
这个 DropdownMenu 类封装了创建一个带有菜单的按钮所需的所有步骤。 */
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
* 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;
|
|
|
|
|
import android.view.Menu;
|
|
|
|
|
import android.view.MenuItem;
|
|
|
|
|
import android.view.View;
|
|
|
|
|
import android.view.View.OnClickListener;
|
|
|
|
|
import android.widget.Button;
|
|
|
|
|
import android.widget.PopupMenu;
|
|
|
|
|
import android.widget.PopupMenu.OnMenuItemClickListener;
|
|
|
|
|
|
|
|
|
|
import net.micode.notes.R;
|
|
|
|
|
|
|
|
|
|
public class DropdownMenu { /*定义了一个名为 DropdownMenu 的公共类*/
|
|
|
|
|
private Button mButton;
|
|
|
|
|
private PopupMenu mPopupMenu;
|
|
|
|
|
private Menu mMenu; /*声明了一些私有变量,分别代表按钮、弹出菜单和菜单对象。*/
|
|
|
|
|
|
|
|
|
|
public DropdownMenu(Context context, Button button, int menuId) {
|
|
|
|
|
mButton = button;
|
|
|
|
|
mButton.setBackgroundResource(R.drawable.dropdown_icon); /*构造函数初始化成员变量,设置按钮的背景图片*/
|
|
|
|
|
mPopupMenu = new PopupMenu(context, mButton);
|
|
|
|
|
mMenu = mPopupMenu.getMenu();
|
|
|
|
|
mPopupMenu.getMenuInflater().inflate(menuId, mMenu);/*创建 PopupMenu 实例,获取菜单对象,并通过提供的菜单资源 ID 充气菜单*/
|
|
|
|
|
mButton.setOnClickListener(new OnClickListener() {
|
|
|
|
|
public void onClick(View v) {
|
|
|
|
|
mPopupMenu.show();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} /*为按钮设置点击监听器,点击时显示弹出菜单*/
|
|
|
|
|
|
|
|
|
|
public void setOnDropdownMenuItemClickListener(OnMenuItemClickListener listener) {
|
|
|
|
|
if (mPopupMenu != null) {
|
|
|
|
|
mPopupMenu.setOnMenuItemClickListener(listener);
|
|
|
|
|
}
|
|
|
|
|
} /*设置弹出菜单项点击监听器的方法,允许外部设置监听器以便处理菜单项点击事件*/
|
|
|
|
|
|
|
|
|
|
public MenuItem findItem(int id) {
|
|
|
|
|
return mMenu.findItem(id);
|
|
|
|
|
} /*提供一个方法用于根据资源 ID 查找菜单项*/
|
|
|
|
|
|
|
|
|
|
public void setTitle(CharSequence title) {
|
|
|
|
|
mButton.setText(title);
|
|
|
|
|
}/*设置按钮文本的方法*/
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/*这个 DropdownMenu 类使得在应用程序中添加带有弹出菜单的按钮变得更加容易,通过构造函数传入上下文、按钮和菜单资源 ID,就可以轻松地创建和使用带有菜单的按钮。*/
|