cordova-Toast的使用 -官方插件和自定义插件


前言:cordova是使用前端技术来开发app,可以节省成本和快速发布。不需要了解原生app开发
加载web的方式,可以兼容生成Android、ios以及浏览器等各种平台的项目
前文:cordova开发流程



一、官方提示浮动框 cordova-plugin-x-toast

1.cordova plugin add cordova-plugin-x-toast

2.在index.js文件中添加以下方法

3.在合适地方调用Toast方法

//Toast提示
function showToastTop(msg) {
    
    
  console.log("showToastTop:"+ msg);
  window.plugins.toast.showWithOptions(
    {
    
    
      message: msg,
      duration: 10000, // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
      position: "top",
          styling: {
    
    
            opacity: 0.75, // 0.0 (transparent) to 1.0 (opaque). Default 0.8
            backgroundColor: '#F5F5F5', // make sure you use #RRGGBB. Default #333333
            textColor: '#000000', // Ditto. Default #FFFFFF
            textSize: 16, // Default is approx. 13.
            cornerRadius: 100, // minimum is 0 (square). iOS default 20, Android default 100
            horizontalPadding: 20, // iOS default 16, Android default 50
            verticalPadding: 16 // iOS default 12, Android default 30
          },
      addPixelsY: 40  // added a negative value to move it up a bit (default 0)
    },
    onSuccess, // optional
    onError    // optional
  );
}
  function onSuccess() {
    
    
   console.log("onSuccess :"+message);
     };
   function onError(message) {
    
    
    console.log('onError:'+message);
    };


二、自定义的Toast

自定义 Cordova插件详解
自定义Toast目录

以上目录你可以手动创建这几个目录及文件,也可以用命令行自动创建,推荐的方式是使用plumam。

1、首先安装plumam命令行工具
npm install -g plugman

2、安装完之后,创建plugin
使用plumam创建插件的命令是:
plugman create --name pluginName --plugin_id pluginID --plugin_version version [–path path] [–variable NAME=VALUE]

参数说明:
pluginName:插件名称,如MyToast;
pluginID:插件id, 如:org.demo.mytoast;
version:版本号, 如:0.0.1;
path:插件存放的绝对或相对路径;
variable NAME=VALUE:扩展参数,如说明或作者,如woodstream

于是命令行中敲入以下代码:
plugman create --name MyToast --plugin_id org.demo.mytoast --plugin_version 0.0.1

plugin.xml

<?xml version='1.0' encoding='utf-8'?>
<plugin xmlns:android="http://schemas.android.com/apk/res/android" id="com.jlc.customtoast" version="1.0.0"
    xmlns="http://apache.org/cordova/ns/plugins/1.0">
    <name>MyToast</name>
    <js-module name="MyToast" src="www/MyToast.js">
        <clobbers target="cordova.plugins.MyToast" />
    </js-module>
    <platform name="android">
        <config-file parent="/*" target="res/xml/config.xml">
            <feature name="MyToast">
                <param name="android-package" value="com.jlc.customtoast.MyToast" />
            </feature>
        </config-file>
        <config-file parent="/*" target="AndroidManifest.xml"></config-file>
        <source-file src="src/android/MyToast.java" target-dir="src/com/jlc/customtoast/MyToast" />
    </platform>
</plugin>
  • id:插件唯一标识
  • version:版本号
  • js-module
    src:js中间件相对文件地址(www目录下的那个js)
    name:模块名称
    clobbers/merges
    target:H5通过它调用js中间件方法(ts调用方法的前缀)
  • platform
    name:对应平台android | ios
    source-file
    src:类名
    tartget-dir:插件文件复制到到原生项目位置
    feature
    name:js中间件通过它调用原生方法(包名)
    uses-permission:相关原生权限

插件转android的java文件

package com.luoyang.myplugin;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.apache.cordova.CordovaArgs;
import android.view.Gravity;
import android.widget.TextView;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;


/**
* This class echoes a string called from JavaScript.
*/
public class MyToast extends CordovaPlugin {
    
    
    private static final int GRAVITY_TOP = Gravity.TOP|Gravity.CENTER_HORIZONTAL;


    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    
    
        if (action.equals("showToast")) {
    
    
            this.showToast(args, callbackContext);
            return true;
        }
        return false;
    }

    /**
     * 显示toast的原生方法
     */
    private boolean showToast(JSONArray args, CallbackContext callbackContext) {
    
    
        try {
    
    
            CordovaArgs cordovaArgs = new CordovaArgs(args);
            //custom.js中的text内容
            String text = cordovaArgs.getJSONObject(0).getString("text");
            final android.widget.Toast toast= android.widget.Toast.makeText(cordova.getActivity().getApplicationContext(), text, Toast.LENGTH_LONG);
            //位置设置为顶部,偏移60
            toast.setGravity(GRAVITY_TOP, 0, 60);
            // 设置shape
            GradientDrawable shape = new GradientDrawable();
            shape.setCornerRadius(100);
            shape.setAlpha((int)(0.75 * 255)); // 0-255, where 0 is an invisible background
            shape.setColor(Color.parseColor("#F5F5F5"));
            toast.getView().setBackground(shape);
            //设置padding
            toast.getView().setPadding(50, 30, 50, 30);
            //设置字体大小
            final TextView toastTextView;
            toastTextView = (TextView) toast.getView().findViewById(android.R.id.message);
            toastTextView.setTextColor(Color.parseColor("#000000"));
            toastTextView.setTextSize(16f);
            //展示
            toast.show();
            callbackContext.success();
            return true;
        } catch (Exception e) {
    
    
            e.printStackTrace();
            callbackContext.error("toast显示异常");
            return false;
        }
    }
}

具体内容的转化为js调用

var exec = require('cordova/exec');

exports.showToast = function (arg0, success, error) {
    
    
    exec(success, error, 'MyToast', 'showToast', [arg0]);
};

3、创建package.json文件,一个插件就完成了的,里面的参数从plugin.xml拿过来便是:

{
    
    
  "name": "mytoast",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    
    
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

在index.js即可

cordova.plugins.MyToast.showToast({
    
    text:'你好自定义的Toast1',},onSuccess,onFail)

                          function onSuccess() {
    
    
                                  alert('onSuccess 自定义的Toast' );
                          };

                          function onFail(message) {
    
    
                             alert('Failed 自定义的Toast: '+message);
                          }

创建价值,乐哉分享!

参考文档:自定义 Cordova插件详解

猜你喜欢

转载自blog.csdn.net/ly_xiamu/article/details/128574599