package com.common.widget;

import android.content.Context;
import android.support.annotation.LayoutRes;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;

/**
 * Created by SiKang on 2019/5/21.
 */
public class FloatView {
    private View rootView;
    private Context context;

    public FloatView(Context context) {
        this.context = context;
    }

    public void bindLayout(@LayoutRes int layout, float x, float y, OnLayoutListener onLayoutListener) {
        rootView = LayoutInflater.from(context).inflate(layout, null);
        onLayoutListener.onLayout(rootView);

        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.addView(rootView, rootView.getLayoutParams());
        setLocatioin(x, y);
    }

    public void bindLayout(View view, float x, float y) {
        rootView = view;
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        manager.addView(rootView, layoutParams);
        setLocatioin(x, y);
    }


    private void setLocatioin(float x, float y) {
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);

        WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) rootView.getLayoutParams();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        layoutParams.x = (int) (dm.widthPixels * x);
        layoutParams.y = (int) (dm.heightPixels * y);
        rootView.setLayoutParams(layoutParams);
    }

    public interface OnLayoutListener {
        void onLayout(View view);
    }
}
