Android 创建事件监听
一、在自定义的MyView中
1. 定义监听接口
public interface InterfaceName
{
returnType methodName(Argument list);
}
2.创建监听对象
private InterfaceName interfaceObject;
3.添加设置监听方法
public void setInterfaceName(InterfaceName object)
{
this.interfaceObject = object ;
}
4.触发事件处调用
this.interfaceObject.methodName(Argument list);
5.这样,我们就可以像其他View一样,在Activity等设置监听事件
二、示例
1.自定义创建的菜单按钮,弹出和弹回菜单窗口
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.PopupWindow;
public class MenuBar extends ImageView
{
private PopupWindow popupWindow;
public MenuBar(Context context)
{
super(context);
}
public MenuBar(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void showMenu()
{
LayoutInflater layoutInflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.slide_menu, null);
popupWindow = new PopupWindow(popupView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
popupWindow.showAsDropDown(this, 0, 0);
//Call onPopupWindowListener.onShow when popupWindow showed
if (onPopupWindowListener != null)
{
onPopupWindowListener.onShow(popupWindow);
}
}
public void dismiss()
{
if (popupWindow != null)
{
popupWindow.dismiss();
}
//Call onPopupWindowListener.onDismiss when popupWindow dismissed
if (onPopupWindowListener != null)
{
onPopupWindowListener.onDismiss(popupWindow);
}
}
//set up popupWindow listener inerface
public interface OnPopupWindowListener
{
/**
* Called when popupWindow showed
* @param popupWindow which popupWindow showed
*/
public void onShow(PopupWindow popupWindow);
/**
* Called when popupWindow dismissed
* @param popupWindow which popupWindow dismissed
*/
public void onDismiss(PopupWindow popupWindow);
}
private OnPopupWindowListener onPopupWindowListener;
public void setOnPopupWindowListener(OnPopupWindowListener onPopupWindowListener)
{
this.onPopupWindowListener = onPopupWindowListener;
}
}
2.Activity中设置监听
//listPopupWindowShowing用于存储所有showing的窗口,方便管理
private List<PopupWindow> listPopupWindowShowing=new ArrayList();
private MenuBar menubar=new MenuTitleBar(this);
menubar.setOnPopupWindowListener(new OnPopupWindowListener()
{
@Override
public void onShow(PopupWindow popupWindow)
{
// TODO Auto-generated method stub
listPopupWindowShowing.add(popupWindow);
}
@Override
public void onDismiss(PopupWindow popupWindow)
{
// TODO Auto-generated method stub
listPopupWindowShowing.remove(popupWindow);
}
});
3.这个例子并不好,之后可能会添加百度推送的例子,这是心血来潮的一篇博客,望海涵。
示例来着于开发中,遇到多出弹出窗口,按返回键依序关闭,还有跳转页面全部关闭等问题,就想到里用list存储窗口对象。可是每次创建都去添加,实在太蠢了,要是有一次忘了就麻烦了。所以就想到了用监听,创建时自动去添加等。