安卓与html混合开发之原生与js相互调用

2023-05-16

原生和html的优缺点就不多说了,有些特定条件下用html页面可以很方便,也很容易更新和维护,那么这就涉及到html与安卓原生的交互和通信。

接下来我要分享的是html调用原生的弹窗和位置信息,安卓原生调用JS中的方法。

xml很简单:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:id="@+id/linearlayout"
    android:layout_height="match_parent">
    <include layout="@layout/layout_title"></include>

<WebView
    android:id="@+id/wv_location"
    android:layout_width="match_parent"
    android:layout_height="match_parent"></WebView>

</LinearLayout>

初始化WebView之后就开始加载html以及几个关键代码:

  	webView.setWebChromeClient(new WebChromeClient() );
        webView.getSettings().setJavaScriptEnabled(true);   //开启JavaScript支持

        // 添加一个对象, 让JS可以访问该对象的方法, 该对象中可以调用JS中的方法
        webView.addJavascriptInterface(new JSInterface1(), "baobao");
        webView.setWebViewClient(new MyWebViewClient());
        webView.loadUrl("file:///android_asset/PriseLocation.html");

webView.setWebChromeClient(new WebChromeClient());必不可少,它是解决js中alert不弹出的问题和其它内容的渲染问题。

关键的两行代码说一下,首先是js调用原生的方法:webView.addJavascriptInterface(new JSInterface1(),"baobao");JSInterface1内部类中的方法都是提供给js调用的,“baobao”相当于一个“id”,用于标记原生的对象,被html用来调用原生的方法,就相当于引用一样。另一行重要的代码就是webView.loadUrl("javascript: showMsg()");loadUrl方法内的字符串就是调用js中的方法。

JSInterface1:

class JSInterface1 {

        //JavaScript调用此方法
        @JavascriptInterface

        public void callAndroidMethod(int a, float b, String c, boolean d) {
            if (d) {
                String strMessage = "a+b+c=" + a + b + c;
                T.showThort(mContext, strMessage);

//                showPopupWindowIntroDestine();


            }
        }

        @JavascriptInterface
        public void callLocation() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    //获取Location
                    /**
                     * 获取地理位置
                     */
                    String locaLocation = getLocaLocation();
                }
            });


        }

        @JavascriptInterface
        public void callAlert(final String info) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.getAlert(info, 0.3f);
                }
            });

        }

        /**
         * @param info
         */
        @JavascriptInterface
        public void callConfirm(final String info) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.seConfirmButtonText("确认", "取消");
                    popUtils.getConfirm(info, 0.3f, new PopAlertStyleUtils.CallBackLeftRightButton() {
                        @Override
                        public void rightButton(View v) {
                            popUtils.popDismiss();
                        }

                        @Override
                        public void leftButton(View v) {

                            T.showThort(mContext, "我是左边按钮");
                        }
                    });
                }
            });

        }

        @JavascriptInterface
        public void callPrompt(final String info) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.setLeftRightBtText("继续", "不玩了");
                    popUtils.getPromptWindow(info, 0.3f, new PopAlertStyleUtils.CallBackPrompt() {
                        @Override
                        public void rightButton(View v, EditText editText) {
                            popUtils.popDismiss();
                        }

                        @Override
                        public void leftButton(View v, EditText editText) {
                            T.showThort(mContext, "请继续玩吧-----" + editText.getText().toString());
                        }
                    });
                }
            });
        }


        @JavascriptInterface
        public void callLoading(final String info) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.getLoading(info, 0.3f);
                    new Handler() {
                    }.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            popUtils.popDismiss();
                        }
                    }, 2000);
                }
            });
        }


        @JavascriptInterface
        public void callToast(final String info) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.getToast(info, 1.0f);
                    new Handler() {
                    }.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            popUtils.popDismiss();
                        }
                    }, 2000);
                }
            });
        }

        @JavascriptInterface
        public void callActionsheet() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.setTitle("Who wins");
                    nameList = new ArrayList<String>();
                    nameList.add("张赛宝");
                    nameList.add("小黄");
                    nameList.add("张绍均");
                    nameList.add("杨峰");

                    popUtils.getActionsheet(0.3f, new PopAlertStyleUtils.CallBackActionSheet() {
                        @Override
                        public void backListView(ListView listView, Button button) {

                            button.setText("确定");
                            NameListAdapter adapter = new NameListAdapter(mContext, nameList);
                            listView.setAdapter(adapter);
                            button.setOnClickListener(new ButtonOnclick());
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    webView.loadUrl("javascript: showMsg()");
                                }
                            });
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void callChosen() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.setTitle("Who wins");
                    final List<String> choseList = new ArrayList<>();
                    choseList.add("张赛宝");
                    choseList.add("小黄");
                    choseList.add("张绍均");
                    choseList.add("杨峰");
                    popUtils.getChosen(0.3f, new PopAlertStyleUtils.CallBackChosen() {
                        @Override
                        public void backChosen(ListView listView) {
                            final ChosenAdapter adapter = new ChosenAdapter(mContext, choseList);
                            listView.setAdapter(adapter);
                            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                @Override
                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                    adapter.setSelectNum(position);
                                    adapter.notifyDataSetChanged();
                                }
                            });
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void callModal() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.setTitle("2.5版本更新");
                    popUtils.setLeftRightBtText("了解更多", "知道了");
                    popUtils.getModal("1.功能更新2.功能更新", 0.3f, new PopAlertStyleUtils.CallBackModal() {
                        @Override
                        public void rightButton(View v) {
                            T.showThort(mContext, "我是左边按钮");
                        }

                        @Override
                        public void leftButton(View v) {
                            T.showThort(mContext, "我是右边按钮");
                        }

                        @Override
                        public void initImag(ImageView imageView) {
                            Glide.with(mContext).load(R.mipmap.bg_banner).transform(new GlideRoundTransform(mContext, 15)).into(imageView);
                        }
                    });
                }
            });
        }

        @JavascriptInterface
        public void callTimepicker() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.getDatePicker();
                }
            });
        }

        @JavascriptInterface
        public void callDatepicker() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    final PopAlertStyleUtils popUtils = new PopAlertStyleUtils(mContext, parentsView);
                    popUtils.getTimePicker();
                }
            });
        }

        @JavascriptInterface
        public void btBack() {//返回
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            });

        }

        @JavascriptInterface
        public void btHelp() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(mContext, HelpDemoActivity.class);
                    startActivity(intent);
                }
            });
        }

        @JavascriptInterface
        public void setTitle(final String title) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    tvTitle.setText(title);
                }
            });
        }
    }
Html代码,主要就是通过定义的引用 baobao.XXX()调用原生中的方法,可以传递参数。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
 
    <script src="http://api.map.baidu.com/api?v=1.2" type="text/javascript"></script>

<script>
   function showMsg(){
      alert("hello world!");
   }
function showHelp(){
      alert("我是帮助回调");
   }
function getTitle(){
    var id=document.getElementById("text").value;

    baobao.setTitle(id);
}
   </script>
</head>
<body>
<div className="page-dialog" >
<button  class="btn"onClick="baobao.callAndroidMethod(100,100,'ccc',true)">我是弹窗按钮</button></div>
    <div className="page-dialog" >
<button class="btn"onClick="baobao.callLocation()">我是地理位置按钮</button></div>

<div className="page-dialog" >
    <button class="btn" onClick="baobao.callAlert('我是提示信息')">alert</button></div>
<div className="page-dialog"  >
    <button class="btn" onClick="baobao.callConfirm('我是提示信息')">confirm</button></div>
    <div className="page-dialog">
    <button class="btn" onClick="baobao.callPrompt('我是提示信息')">prompt</button></div>
        <div className="page-dialog">
    <button class="btn" onClick="baobao.callLoading('使劲加载中...')">loading...</button></div>
            <div className="page-dialog">
    <button class="btn" onClick="baobao.callToast('提交成功')">toast</button></div>
                <div className="page-dialog">
    <button class="btn" onClick="baobao.callActionsheet()">actionsheet</button></div>
                    <div className="page-dialog">
    <button class="btn" onClick="baobao.callChosen()">chosen</button></div>
                        <div className="page-dialog">
    <button class="btn" onClick="baobao.callModal()">modal</button></div>
                            <div className="page-dialog">
    <button class="btn" onClick="baobao.callTimepicker()">timepicker</button></div>
                                <div className="page-dialog">
    <button class="btn" onClick="baobao.callDatepicker()">datepicker</button></div>



</div>

<div className="page-dialog">

    <button class="btn" onClick="baobao.btBack()">返回页面</button>
<button class="btn" onClick="baobao.btHelp()">帮助</button>
</div>

<div >
    <input class = "title" id="text"><input type="button" value="修改标题" id="btnn" onclick ="getTitle()">
</div>

</body>
<style>
    .btn{background:#00acff; color:#fff; border-radius:0.1em; width:100%;border:0;margin-top:0.5em;}
</style>
<style>
    .title{margin-top:0.5em;}
</style>
</html>

弹窗工具集合我都是自定义做的会有些麻烦,但是可操作性比较高:

package cn.com.bjhj.baseframework.utils;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;

import java.util.Calendar;

import cn.com.bjhj.baseframework.R;


/**类介绍(必填): 各种样式弹窗
 
 */

public class PopAlertStyleUtils {

    private Context context;
    private View parentsView;
    private View mPopView;
    private CustomPopupWindow mAlertWindow;
    private View mPopViewConfirm;
    private CallBackLeftRightButton callBackLeftRightButton;
    private CustomPopupWindow mConfirmWindow;
    private String confirmLeft;
    private String confirmRight;
    private View mPopViewPrompt;
    private CustomPopupWindow mPromptWindow;
    private String promptLeft;
    private String promptRight;
    private CallBackPrompt callBackPrompt;
    private View mPopViewLoading;
    private CustomPopupWindow mLoadingWindow;
    private View mPopViewToast;
    private CustomPopupWindow mToastWindow;
    private TextView tvAlertHint;
    private String title;//标题
    private View mPopViewActionsheet;
    private CustomPopupWindow mActionsheetWindow;
    private CallBackActionSheet callBackActionSheet;
    private View mPopViewChosen;
    private CustomPopupWindow mChosenWindow;
    private CallBackChosen callBackChosen;
    private View mPopViewModal;
    private CustomPopupWindow mModalWindow;
    private String time;

    public PopAlertStyleUtils(Context context,View parentsView) {
        this.context = context;
        this.parentsView = parentsView;
        if (title!=null){
            title="提示";
        }
    }

    /**
     * 获取提示框 alert
     * @param info 提示信息
     * @param num  背景透明度
     */
    public void getAlert(final String info, float num){
        mPopView = LayoutInflater.from(context).inflate(R.layout.pop_window_alert, null);
        mAlertWindow = new CustomPopupWindow(parentsView,
                context, mPopView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mAlertWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                tvAlertHint = (TextView) mPopView.findViewById(R.id.tv_alert_hint);
                TextView tvAlertInfo = (TextView) mPopView.findViewById(R.id.tv_alert_info);
                Button btAlertObtain = (Button) mPopView.findViewById(R.id.bt_alert_obtain);
                tvAlertInfo.setText(info);
                if (title!=null){
                    tvAlertHint.setText(title);
                }
                btAlertObtain.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popDismiss();
                    }
                });
            }
        });
        mAlertWindow.showView();
        mAlertWindow.setBackgroundAlpha(num);
    }

    /**
     * 设置标题
     * @param title 标题
     */
    public void setTitle(String title){
    this.title = title;
}
    /**
     * 获取confirm对话框
     * @param info
     * @param num
     * @param callBackLeftRightButton
     */
    public void getConfirm(final String info, float num, final CallBackLeftRightButton callBackLeftRightButton){
        this.callBackLeftRightButton = callBackLeftRightButton;
        mPopViewConfirm = LayoutInflater.from(context).inflate(R.layout.pop_window_confirm, null);
        mConfirmWindow = new CustomPopupWindow(parentsView,
                context, mPopViewConfirm, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mConfirmWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                TextView tvConfirmInfo = (TextView) mPopViewConfirm.findViewById(R.id.tv_confirm_info);
                Button btConfirmLeft = (Button) mPopViewConfirm.findViewById(R.id.bt_confirm_left);
                TextView tvConfirmHint = (TextView) mPopViewConfirm.findViewById(R.id.tv_confirm_hint);
                if (title!=null){
                    tvConfirmHint.setText(title);
                }
                Button btConfirmRight = (Button) mPopViewConfirm.findViewById(R.id.bt_confirm_right);
                tvConfirmInfo.setText(info);
                if (confirmLeft!=null&&confirmRight!=null){
                    btConfirmLeft.setText(confirmLeft);
                    btConfirmRight.setText(confirmRight);
                }
                btConfirmLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                      callBackLeftRightButton.leftButton(v);
                    }
                });
                btConfirmRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    callBackLeftRightButton.rightButton(v);
                    }
                });
            }
        });
        mConfirmWindow.showView();
        mConfirmWindow.setBackgroundAlpha(num);
    }

    /**
     * 设置confirm的左右按钮名字
     * @param left
     * @param right
     */
    public void seConfirmButtonText(String left,String right){
    confirmLeft = left;
        confirmRight = right;
}

    /**
     * 获取输入对话框
     * @param info 提示信息
     * @param num  透明度
     * @param callBackPrompt 回调函数
     */
    public void getPromptWindow(final String info, float num, final CallBackPrompt callBackPrompt){
    this.callBackPrompt = callBackPrompt;
    mPopViewPrompt = LayoutInflater.from(context).inflate(R.layout.pop_window_prompt, null);
    mPromptWindow = new CustomPopupWindow(parentsView,
            context, mPopViewPrompt, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
            .LayoutParams.WRAP_CONTENT, true);
//
    /**
     * 初始化悬浮窗 里面的控件
     */
    mPromptWindow.setOnPopupWindowListener(new CustomPopupWindow
            .PopupWindowListener() {

        // TODO 设置活动内容
        @Override
        public void initView() {
            TextView tvPromptInfo = (TextView) mPopViewPrompt.findViewById(R.id.tv_prompt_info);
            TextView tvPromptHint = (TextView) mPopViewPrompt.findViewById(R.id.tv_prompt_hint);
            if (title!=null){
                tvPromptHint.setText(title);
            }
            Button btPromptLeft = (Button) mPopViewPrompt.findViewById(R.id.bt_prompt_left);
            Button btPromptRight = (Button) mPopViewPrompt.findViewById(R.id.bt_prompt_right);
            final EditText etPrompt = (EditText) mPopViewPrompt.findViewById(R.id.et_prompt);

            tvPromptInfo.setText(info);
            if (promptLeft!=null&&promptRight!=null){
                btPromptLeft.setText(promptLeft);
                btPromptRight.setText(promptRight);
            }
            btPromptLeft.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callBackPrompt.leftButton(v,etPrompt);
                }
            });
            btPromptRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    callBackPrompt.rightButton(v,etPrompt);
                }
            });
        }
    });
    mPromptWindow.showView();
    mPromptWindow.setBackgroundAlpha(num);
    
}
    /**
     * 获取prompt弹窗的左右按钮名称
     * @param left
     * @param right
     */
    public void setLeftRightBtText(String left, String right){
        promptLeft = left;
        promptRight = right;
    }
    /**
     * 获取加载中弹窗
     * @param info 加载信息
     * @param num 背景透明度
     */
    public void getLoading(final String info, float num){
        mPopViewLoading = LayoutInflater.from(context).inflate(R.layout.pop_window_loading, null);
        mLoadingWindow = new CustomPopupWindow(parentsView,
                context, mPopViewLoading, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mLoadingWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                TextView tvLoadingInfo = (TextView) mPopViewLoading.findViewById(R.id.tv_load_info);
                tvLoadingInfo.setText(info);

            }
        });
        mLoadingWindow.showView();
        mLoadingWindow.setBackgroundAlpha(num);
    }

    /**
     * 获取吐司弹窗
     * @param info 提示信息
     * @param num 背景透明度
     */
    public void getToast(final String info, float num){
        mPopViewToast = LayoutInflater.from(context).inflate(R.layout.pop_window_toast, null);
        mToastWindow = new CustomPopupWindow(parentsView,
                context, mPopViewToast, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mToastWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                TextView tvToastInfo = (TextView) mPopViewToast.findViewById(R.id.tv_toast_info);
                tvToastInfo.setText(info);

            }
        });
        mToastWindow.showView();
        mToastWindow.setBackgroundAlpha(num);
    }

    /**
     * 获取 选择
     * @param num
     * @param callBackActionSheet
     */
    public void getActionsheet(float num, final CallBackActionSheet callBackActionSheet){
        this.callBackActionSheet=callBackActionSheet;
        mPopViewActionsheet = LayoutInflater.from(context).inflate(R.layout.pop_window_actionsheet, null);
        mActionsheetWindow = new CustomPopupWindow(parentsView,
                context, mPopViewActionsheet, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mActionsheetWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                 TextView tvActionsheetHint = (TextView) mPopViewActionsheet.findViewById(R.id.tv_actionsheet_hint);
                ListView lvActionSheet = (ListView) mPopViewActionsheet.findViewById(R.id.lv_actionsheet);

                Button btActionsheetObtain = (Button) mPopViewActionsheet.findViewById(R.id.bt_actionsheet_obtain);
                if (title!=null){
                    tvActionsheetHint.setText(title);
                }
                callBackActionSheet.backListView(lvActionSheet,btActionsheetObtain);

            }
        });
        mActionsheetWindow.showView();
        mActionsheetWindow.setBackgroundAlpha(num);
    }

    /**
     * 获取单选项
     * @param num
     * @param callBackChosen
     */
    public void getChosen(float num, final CallBackChosen callBackChosen){
        this.callBackChosen = callBackChosen;
        mPopViewChosen = LayoutInflater.from(context).inflate(R.layout.pop_window_chosen, null);
        mChosenWindow = new CustomPopupWindow(parentsView,
                context, mPopViewChosen, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mChosenWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                TextView tvHint = (TextView) mPopViewChosen.findViewById(R.id.tv_chosen_hint);
                if (title!=null){
                    tvHint.setText(title);
                }
                ListView radioGroup = (ListView) mPopViewChosen.findViewById(R.id.lv_chosen);
                callBackChosen.backChosen(radioGroup);

            }
        });
        mChosenWindow.showView();
        mChosenWindow.setBackgroundAlpha(num);
    }

    /**
     * 获取modal
     * @param info
     * @param num
     * @param callBackModal
     */
    public void getModal(final String info, float num, final CallBackModal callBackModal){
        mPopViewModal = LayoutInflater.from(context).inflate(R.layout.pop_window_modal, null);
        mModalWindow = new CustomPopupWindow(parentsView,
                context, mPopViewModal, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout
                .LayoutParams.WRAP_CONTENT, true);
//
        /**
         * 初始化悬浮窗 里面的控件
         */
        mModalWindow.setOnPopupWindowListener(new CustomPopupWindow
                .PopupWindowListener() {

            // TODO 设置活动内容
            @Override
            public void initView() {
                TextView tvModalInfo = (TextView) mPopViewModal.findViewById(R.id.tv_modal_info);
                TextView tvModalHint = (TextView) mPopViewModal.findViewById(R.id.tv_modal_hint);
                ImageView ivPic = (ImageView) mPopViewModal.findViewById(R.id.iv_modal_info);
                if (title!=null){
                    tvModalHint.setText(title);
                }
                Button btModalLeft = (Button) mPopViewModal.findViewById(R.id.bt_modal_left);
                Button btModalRight = (Button) mPopViewModal.findViewById(R.id.bt_modal_right);
                callBackModal.initImag(ivPic);
                tvModalInfo.setText(info);
                if (promptLeft!=null&&promptRight!=null){
                    btModalLeft.setText(promptLeft);
                    btModalRight.setText(promptRight);
                }
                btModalLeft.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callBackModal.leftButton(v);
                    }
                });
                btModalRight.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        callBackModal.rightButton(v);
                    }
                });
            }
        });
        mModalWindow.showView();
        mModalWindow.setBackgroundAlpha(num);

    }
    public void getDatePicker(){
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(context,
                mDateSetListener,
                mYear, mMonth, mDay).show();
    }
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year,
                              int monthOfYear, int dayOfMonth) {

        }
    };
    public void getTimePicker(){
        final Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR);
        int mMonth = c.get(Calendar.MONTH);
        int mDay = c.get(Calendar.DAY_OF_MONTH);
        new TimePickerDialog(context,mTimeSetListener,0,0,true).show();
    }
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        }
    };
    /**
     * 关闭弹窗
     */
    public void popDismiss(){
        if (mAlertWindow!=null){
            mAlertWindow.dismiss();
        }
        if (mConfirmWindow!=null){
            mConfirmWindow.dismiss();
        }
        if (mPromptWindow!=null){
            mPromptWindow.dismiss();
        }
        if (mLoadingWindow!=null){
            mLoadingWindow.dismiss();
        }
        if (mToastWindow!=null){
            mToastWindow.dismiss();
        }
        if (mActionsheetWindow!=null){
            mActionsheetWindow.dismiss();
        }
    }

    /**
     * 没有输入框的左右按钮回调
     */
    public interface CallBackLeftRightButton {
        public void rightButton(View v);
        public void leftButton(View v);
    }

    /**
     * 有输入框的左右回调
     */
    public interface CallBackPrompt {
        public void rightButton(View v,EditText editText);
        public void leftButton(View v,EditText editText);
    }
    public interface CallBackActionSheet{
        void backListView(ListView listView,Button button);
    }
    public interface CallBackChosen{
        void backChosen(ListView listView);
    }
    public interface CallBackModal{
        public void rightButton(View v);
        public void leftButton(View v);
        void initImag(ImageView imageView);
    }
    }
自定义PopWindow:

package cn.com.bjhj.baseframework.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

/**
 * 自定义悬浮窗体
 * Created by JIANG on 2016/8/5.
 */
public class CustomPopupWindow implements PopupWindow.OnDismissListener {
    private PopupWindowListener mPopupWindowListener;
    public PopupWindow mPopupWindow;
    private Activity mActivity;
    private Context context;
    private View mParentView;
    private int mWidth;
    private int mHeight;
    private View mPopupWindowView;
    private boolean focusable;
    private View dropDown =null;


    public CustomPopupWindow(View parentView, Context activity, View contentView, int width, int
            height, boolean focusable) {
        this.mActivity = (Activity) activity;
        this.context = activity;
        this.mParentView = parentView;
        this.mWidth = width;
        this.mHeight = height;
        this.focusable = focusable;
        this.mPopupWindowView = contentView;
    }
    public CustomPopupWindow(View dropDown, View parentView, Context activity, View contentView, int width, int
            height, boolean focusable) {
        this.mActivity = (Activity) activity;
        this.context = activity;
        this.mParentView = parentView;
        this.mWidth = width;
        this.mHeight = height;
        this.focusable = focusable;
        this.mPopupWindowView = contentView;
        this.dropDown = dropDown;
    }

    /**
     * 显示PopupWindow
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    public void showView() {
        mPopupWindow = new PopupWindow(mPopupWindowView, mWidth, mHeight, focusable);
        if (mPopupWindowListener != null) {
            mPopupWindowListener.initView();
        }

        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0xFFFFFF));

        mPopupWindow.update();
        mPopupWindow.setOnDismissListener(this);
        if (dropDown!=null) {

            // 计算x轴方向的偏移量,使得PopupWindow在Title的正下方显示,此处的单位是pixels
            float xoffInPixels = ScreenUtils.getScreenWidth(context) / 2 ;
            // 将pixels转为dip
            int xoffInDip = ScreenUtils.px2dip(context,xoffInPixels);

            mPopupWindow.showAsDropDown(dropDown,0,0);

        }else {
            mPopupWindow.showAtLocation(mParentView, Gravity.CENTER | Gravity.CENTER, 0, 0);
        }

    }

    /**
     * 点击悬浮窗外面时的操作
     */
    @Override
    public void onDismiss() {
        setBackgroundAlpha(1f);
    }

    public interface PopupWindowListener {
        // 初始化PopupWindow的控件
        void initView();
    }

    public void setOnPopupWindowListener(PopupWindowListener listener) {
        this.mPopupWindowListener = listener;
    }

    /**
     * 隐藏PopupWindow
     */
    public void dismiss() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
            mPopupWindow = null;
        }
    }

    //设置屏幕背景透明效果
    public void setBackgroundAlpha(final float alpha) {
        mActivity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                WindowManager.LayoutParams lp = mActivity.getWindow().getAttributes();
                mActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                lp.alpha = alpha;
                mActivity.getWindow().setAttributes(lp);
            }
        });

    }
}



效果图:


各个弹窗的效果如下:


效果大概就是这些,还有一个是调用js中的方法然后弹窗显示我就不展示了。获取地理位置和这个弹窗原理是一样的,具体操作请看我另一篇博文。http://blog.csdn.net/jhl122/article/details/53205345。 博客上还有另一种简便的方式弹窗,有兴趣的请看http://blog.csdn.net/u012124438/article/details/53371102。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

安卓与html混合开发之原生与js相互调用 的相关文章

  • 使用阿里云的函数计算来实现OSS资源的打包下载

    文档地址 xff1a 如何使用函数计算将多个文件打包下载到本地 对象存储 OSS 阿里云 计算函数可以通过对外公网域名进行访问 xff1a 计算函数的参数有几个 xff1a bucket xff1a 使用的OSS的bucket xff0c
  • linux系统上nodejs 报错:node: /lib/x86_64-linux-gnu/libm.so.6: version `GLIBC_2.27‘ not found

    原因 xff1a 因为当前系统不支持GLIBC 2 27 xff0c 而且node的版本过高 xff0c 但是后来降低了版本还是报这个错误 xff0c 后来发现低版本的软链接在 usr bin xff0c 而高版本的软链接在 usr loc
  • 使用nvm控制nodejs版本

    原因 xff1a 由于项目需要用到两个版本的nodejs xff0c 如果只是一个版本的nodejs的话 xff0c 其中一个项目就会报错 xff0c 所以需要用到nvm进行nodejs版本控制 xff0c 使用不同版本的nodejs来进行
  • opencv 实战案例 (一)

    目录 xff1a 1 用 Canny 算子检测图像轮廓提取车道线任务 xff08 Canny xff09 2 用 findContours 发现硬币轮廓任务 Canny 43 findContours 3 用概率霍夫变换检测车道线任务 Ca
  • 企业微信-构造网页授权链接实现登录

    文档地址 xff1a 构造网页授权链接 接口文档 企业微信开发者中心 注意 xff1a 1 redirect uri xff1a 回调链接地址 xff0c 需要使用urlencode对链接进行处理 2 scope xff1a 如果需要获取成
  • dpkg: 处理软件包 xxx (--configure)时出错解决方法

    问题 xff1a dpkg 处理软件包 libicu dev configure 时出错 xff1a 依赖关系问题 仍未被配置 dpkg 依赖关系问题使得 libxml2 dev amd64 的配置工作不能继续 xff1a libxml2
  • oracle 删除表以及回复数据

    找回删除的表 select object name original name partition name type ts name createtime droptime from recyclebin WHERE original n
  • 银行卡信息查询

    银行卡bin 银行卡信息 请移步到github xff1a https github com burningmyself bank
  • ProcessDefinition是干这个用的

    流程定义ProcessDefinition是对业务过程的完整描述 xff0c 例如请假流程定义 报销流程定义等 流程定义的管理包括部署流程定义 查询流程定义 查看流程定义图和删除流程定义 1 部署流程定义 使用RepositoryServi
  • 截取字符串的三种方法

    众所周知 xff0c java提供了很多字符串截取的方式 下面就来看看大致有几种 span class hljs number 1 span span class hljs built in split span 43 正则表达式来进行截取
  • Iterator主要有三个方法:hasNext()、next()、remove()详解

    一 Iterator的API 关于Iterator主要有三个方法 xff1a hasNext next remove hasNext 没有指针下移操作 xff0c 只是判断是否存在下一个元素 next xff1a 指针下移 xff0c 返回
  • @ModelAttribute用法详解

    转载于 xff1a https blog csdn net harry zh wang article details 57329613 之前项目中并自己并没有怎么使用到过 64 ModelAttribute这个注解 xff0c 接手一个老
  • mysql除法运算保留小数的用法

    参照 xff1a https www cnblogs com owenma p 7097602 html 在工作中会遇到计算小数而且需要显现出小数末尾的0 xff0c 我们会用到DECIMAL这个函数 xff0c 这是一个函数非常强悍 xf
  • IDEA—点击文件代码与目录自动同步对应

    关注微信公众号 xff1a CodingTechWork xff0c 一起学习进步 引言 在使用IDEA的时候 xff0c 我们Ctrl 43 Shift 43 F搜索文件后 xff0c 总是要慢慢找文件在哪个包路径下 如查看路径顶端 xf
  • springboot打包完成之后无法读取到resources下的资源文件

    File privateKeyFile 61 ResourceUtils getFile classpath wx pfx PrivateKey privateKey 61 getPrivateKey privateKeyFile priv
  • 接口签名实现拦截的两种方式

    1 采用spring的aop思想进行拦截 需要自定义注解 xff0c 然后定义切面 xff08 五大类 xff09 然后在定义 xff0c 可以获取所有的参数 2 拦截器的实现方式 自定义拦截器 xff0c 然后对拦截器进行配置即可 配置
  • Java程序员利器,lombok神搭档:delombok插件

    Lombok是一款非常实用Java工具 xff0c 它可以帮助开发人员减少样板代码 xff0c 使开发人员专注业务逻辑 xff0c 在Java界几乎无人不知 但也有一些明显的缺点 xff0c 例如 xff1a 对插件强依赖 xff0c 在团
  • C++bind函数

    1 基本概念 bind函数定义在头文件 functional 中 可以将 bind 函数看作一个通用的函数适配器 xff0c 它接受一个可调用对象 xff0c 生成一个新的可调用对象来 适应 原对象的参数列表 C 43 43 Primer
  • C++值的分类 —— 摘自维基百科

    在C 43 43 11 xff0c 对于值的分类 xff0c 要考虑标识 xff08 identity xff09 与可移动性 xff08 movability xff09 xff0c 二者的组合产生了五种分类 xff1a 基础值类型 左值
  • pytorch 深度学习入门代码 (一)线性回归代码实现

    34 34 34 一维线性回归代码实现 34 34 34 import torch from torch autograd import Variable import matplotlib pyplot as plt import tor

随机推荐

  • pytorch 深度学习入门代码 (三)Logistic 回归代码实现

    span class hljs string 34 34 34 Logistic 回归的代码实现 34 34 34 span span class hljs keyword import span matplotlib pyplot spa
  • pytorch 深度学习入门代码 (四)多层全连接神经网络实现 MNIST 手写数字分类

    net py span class hljs keyword import span torch nn span class hljs keyword as span nn span class hljs class span class
  • CentOs云服务器部署项目全流程

    目录 序工具准备putty安装及使用pscp安装及使用 环境安装及配置serverjre 或jdk 安装及配置mysql安装及配置Tomcat 安装及配置 项目部署上传war包至服务器tomcat无法启动常见问题去除端口号和目录名访问项目项
  • 快速上手MybatisPlus

    首先附上mybatis plus官方文档 本篇参考官方文档记录spring mvc项目接入mybatis plus的全流程及一些问题的解决方案 xff0c 建议优先参考官方文档 开始之前 xff0c 假设数据库已建好并已能正常访问 依赖配置
  • FTP工具类一

    public class FTPClientUtils public static String FTPCONFIG 61 34 config ftpConfig properties 34 private static String LO
  • 在 SourceTree 中使用 git rebase (变基)

    原始状态 假如我们要在 master 分支上进行开发 xff0c 在远端的 master 分支上右键 xff0c 检出 一个自己的开发分支 dev 1 做一些开发 xff0c 提交到本地 xff0c 不要推送 xff08 push xff0
  • 云服务器搭建部署全流程

    本篇记录在centos7 3上部署web项目的全流程及一些问题的解决方案 工具准备 putty安装及使用 PuTTY可用来在windows上连接linux服务器 xff0c 可去PuTTY官网下载安装如果不想每次登录都输入密码 xff0c
  • 三种获取字节码对象的方式及区别

    方式一 xff1a 对象 getClass 方法是 根对象Object的方法 是其他类继承Object的getClass方法 方式二 xff1a 类名 class xff0c 你可以理解为字节码本身就是静态的 xff0c 类加载的时字节码就
  • 关于接口与Object 类的关系

    看到这个标题 xff0c 你或许就会想好自己的那份答案 但事实上这个确实没有答案 xff0c 至少没官方证明它们之间的基友关系 看法一 xff1a 因为老师说 xff0c 你可以把接口看作是特殊的类 xff0c 所以不假思索的就认为接口也
  • 单词博弈Java实现(借鉴“miss若尘”博客中写的解题思路)

    单词博弈Java实现 xff0c 已经通过庞果网的用例测试 代码如下 import java util HashMap public class WordGameFinalTest public static int who String
  • mysql安装时的粗心错误:last error unable to update security settings. access denied for user 'root' @ 'localh

    来自 梦想家haima 39 s blog gt http blog dreamwe cn 这个报错出现在mysql最后 当你看到mysql的最后一步需要设置密码可能你开心得很 Mysql就快安装好了 赶快输入三行密码都是root 结果报下
  • @SuppressWarnings

    简介 xff1a java lang SuppressWarnings是J2SE 5 0中标准的Annotation之一 可以标注在类 字段 方法 参数 构造方法 xff0c 以及局部变量上 作用 xff1a 告诉编译器忽略指定的警告 xf
  • 欢迎使用CSDN-markdown编辑器

    欢迎使用Markdown编辑器写博客 本Markdown编辑器使用StackEdit修改而来 xff0c 用它写博客 xff0c 将会带来全新的体验哦 xff1a Markdown和扩展Markdown简洁的语法代码块高亮图片链接和图片上传
  • Linux之强大的awk

    来自 梦想家 Haima s blog gt http blog dreamwe cn awk简介 awk是Linux中的一个命令 xff0c 用来做文本处理与分析 xff0c 功能简单强悍 xff0c 同时它也是一门编程语言 awk处理文
  • 手机抓包charles使用

    使用的是charles window 之前使过fiddler但是感觉并没有charles好用以及一目了然 链接 https pan baidu com s 1NMNXa8M4niLObQKIsCNL3A 提取码 2wsa 安装包可以通过连接
  • 安卓Tinker热更新接入踩坑(minSdkVersion 21)

    哎哟 xff0c 这个坑啊 我项目采用的是ARouter 43 Tinker 我接入的是tinkerpathchttp www tinkerpatch com Docs intro按照文档对接 xff0c 我采用的是reflectAppli
  • Android 解压和重新打包system.img

    开始我们的工作前 xff0c 请记住 xff0c Linux一定要学会用file命令分析文件类型 xff0c 这样才好入手 xff0c 否则错了都不知道怎么回事 xff01 xff01 xff01 1 解压system img 先用file
  • Jetpack系列学习笔记整理一 之LifeCycles

    学习最好的途径就是官网和github Demo xff0c 先放链接 xff0c 想看自行跳转 xff1a 官网 xff1a https developer android com topic libraries architecture
  • 获取安卓位置信息

    别忘了添加权限 xff1a lt uses permission android name 61 34 android permission INTERNET 34 gt lt uses permission android name 61
  • 安卓与html混合开发之原生与js相互调用

    原生和html的优缺点就不多说了 xff0c 有些特定条件下用html页面可以很方便 xff0c 也很容易更新和维护 xff0c 那么这就涉及到html与安卓原生的交互和通信 接下来我要分享的是html调用原生的弹窗和位置信息 xff0c