首页 > 代码库 > 创建自定义布局,实现接口回调方法

创建自定义布局,实现接口回调方法

//自定义布局
public class MyLayout extends RelativeLayout{
    
    private Context mContext;
    private ICallBack mCallBack;

    public void setCallBack(ICallBack  cb){
        mCallBack = cb;
    }

    /**
     * 接口
     */
    public interface ICallBack{
        public void update();
    }

 public boolean onTouchEvent(android.view.MotionEvent event) {
 	//调用接口方法	
	  if(mCallBack != null){
            mCallBack.update();
          }
        return false;
        };
     

      //布局初始化
    public MyLayout(Context context) {
        super(context);
        
        mContext = context;
        LayoutInflater.from(context).inflate(R.layout.mylayout, this);
        View v = findViewById(R.id.layout_name);
        
	......
	}
}
可在Activity中创建上面的布局实现其接口方法来刷新ui等操作
private WindowManager mWindowManager;  
private WindowManager.LayoutParams wmParams; 
    //创建布局并实现接口方法
    public void createMyLayout(){
	    wmParams = new WindowManager.LayoutParams();  
	    mWindowManager = getWindowManager(mContext);

            mLayout = new MyLayout (mContext);
            if (wmParams == null) {
                wmParams = new LayoutParams();

                wmParams.type = LayoutParams.TYPE_PHONE;
                wmParams.format = PixelFormat.RGBA_8888;
                wmParams.gravity = Gravity.LEFT | Gravity.TOP;
             //不可聚焦
            //    wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE; 

                //设置窗口长宽数据    
                wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  
                wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  
                //设置x,y轴坐标
                wmParams.x = 0;
                wmParams.y = 0;
          }
	    //将布局添加到窗口
            mWindowManager.addView(mLayout, wmParams);
           //实现接口方法
            mLayout.setCallBack(new ICallBack() {
                
                @Override
                public void update() {
                    //实现方法
			......
                }
            });
            
        }
	}

创建自定义布局,实现接口回调方法