The use of cordova-Toast - official plug-ins and custom plug-ins


Preface: Cordova uses front-end technology to develop apps, which can save costs and release quickly. No need to understand native app development
The way to load the web is compatible with generating projects on various platforms such as Android, ios, and browsers
Previous article: cordova development process



1. The official prompt floating box cordova-plugin-x-toast

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

2. Add the following method to the index.js file

3. Call the Toast method in an appropriate place

//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);
    };


2. Custom Toast

Detailed explanation of custom Cordova plug-ins
Customize the Toast directory

You can manually create these directories and files, or use the command line to create them automatically. The recommended way is to use plumam.

1. First install the plumam command line tool
npm install -g plugman

2. After installation,
the command to create a plugin and use plumam to create a plugin is:
plugman create --name pluginName --plugin_id pluginID --plugin_version version [–path path] [–variable NAME=VALUE]

Parameter description:
pluginName: plugin name, such as MyToast;
pluginID: plugin id, such as: org.demo.mytoast;
version: version number, such as: 0.0.1;
path: absolute or relative path where the plugin is stored;
variable NAME=VALUE: Extended parameters like description or author like woodstream

So type the following code on the command line:
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: the unique identifier of the plugin
  • version: version number
  • js-module
    src: relative file address of js middleware (the js in www directory)
    name: module name
    clobbers/merges
    target: H5 calls js middleware method through it (prefix of ts calling method)
  • platform
    name: corresponding platform android | ios
    source-file
    src: class name
    targetget-dir: copy the plug-in file to the native project location
    feature
    name: js middleware calls the native method (package name) through it
    uses-permission: related native permissions

Plug-in to android java file

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;
        }
    }
}

The conversion of specific content into js calls

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

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

3. Create a package.json file, and a plug-in is completed. The parameters in it are taken from plugin.xml:

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

In index.js you can

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

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

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

Create value, happy to share!

Reference document: Detailed explanation of custom Cordova plug-ins

Supongo que te gusta

Origin blog.csdn.net/ly_xiamu/article/details/128574599
Recomendado
Clasificación