WebView Android Studio中的JavaScript控件

时间:2018-07-27 06:29:13

标签: javascript android android-webview

我的应用程序会自动填写用webview输入的字段。

示例:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Btn1 = (Button)findViewById(R.id.btn1);
        Btn1.setOnClickListener(this);

        webview = (WebView)findViewById(R.id.webview) ;
        webview.getSettings().setJavaScriptEnabled(true);
        webview.setWebViewClient(new WebViewClient());
        webview.loadUrl("https://demo.com/");

    }
     public void onClick(View view) {
       if(view.getId()==Btn1.getId())
       {
            webview.loadUrl("javascript: (function() {document.getElementById('txt_login_email').value= 'demo@gmail.com';}) ();");
            webview.loadUrl("javascript: (function() {document.getElementById('txt_login_password').value= 'demo';}) ();");
            webview.loadUrl("javascript: (function() {document.getElementById('lnkLogin').click();})();");
       }

TextView像这样填满。但是我无法发送该值,因为评分控制台页面上没有id。我了解这里使用了JavaScript。

<div class="rating-option mratingslide_1" data-optionid="15552" rating="2" selected-fill="#FFC385"><div class="icon" style="transform: scale(1);"><svg width="100%" height="100%" viewBox="0 0 50 50"><path d="M50,25 C50,38.807 38.807,50 25,50 C11.193,50 0,38.807 0,25 C0,11.193 11.193,0 25,0 C38.807,0 50,11.193 50,25" class="base" fill="#C6CCD0"></path><path d="M25,31.9996 C21.7296206,31.9996 18.6965022,32.5700242 15.3353795,33.7542598 C14.2935825,34.1213195 13.7466,35.2634236 14.1136598,36.3052205 C14.4807195,37.3470175 15.6228236,37.894 16.6646205,37.5269402 C19.617541,36.4865279 22.2066846,35.9996 25,35.9996 C28.1041177,35.9996 31.5196849,36.5918872 33.0654841,37.4088421 C34.0420572,37.924961 35.2521232,37.5516891 35.7682421,36.5751159 C36.284361,35.5985428 35.9110891,34.3884768 34.9345159,33.8723579 C32.7065288,32.6948667 28.6971052,31.9996 25,31.9996 Z" class="mouth" fill="#FFFFFF"></path><path d="M30.7014384,16.8148522 C30.8501714,16.5872449 31.0244829,16.3714627 31.2243727,16.1715729 C32.054483,15.3414625 33.1586746,14.9524791 34.2456496,15.0046227 C34.8805585,15.7858887 34.945378,15.8599243 35.5310714,16.593811 C36.1167648,17.3276978 36.1439252,17.3549194 36.5988813,17.9093628 C37.0538374,18.4638062 37.2801558,18.7149658 38,19.6496386 C37.8693903,20.4473941 37.496466,21.2131881 36.8812269,21.8284271 C35.3191298,23.3905243 32.7864699,23.3905243 31.2243727,21.8284271 C29.8621654,20.4662198 29.6878539,18.3659485 30.7014384,16.8148522 Z" class="right-eye" fill="#FFFFFF"></path><path d="M18.8284271,21.8284271 C20.1906345,20.4662198 20.3649459,18.3659485 19.3513614,16.8148522 C19.2026284,16.5872449 19.0283169,16.3714627 18.8284271,16.1715729 C17.9983168,15.3414625 16.8941253,14.9524791 15.8071502,15.0046227 C15.1722413,15.7858887 15.1074218,15.8599243 14.5217284,16.593811 C13.9360351,17.3276978 13.9088746,17.3549194 13.4539185,17.9093628 C12.9989624,18.4638062 12.772644,18.7149658 12.0527998,19.6496386 C12.1834095,20.4473941 12.5563339,21.2131881 13.1715729,21.8284271 C14.73367,23.3905243 17.26633,23.3905243 18.8284271,21.8284271 Z" class="left-eye" fill="#FFFFFF"></path></svg></div><div class="label" style="transform: translateY(0px); color: rgb(171, 178, 182);">2<div class="" style=""></div> </div><div class="touch-marker"></div></div>

Js代码:

var RatingControl = function (element) {
	//console.log('rating');
    var self = this;
    self.containerElement = element;
    self.selectedRatingElement = self.containerElement.querySelector(".current-rating");
	//console.log(self.selectedRatingElement);
    self.selectedRatingSVGContainer = self.selectedRatingElement.querySelector(".svg-wrapper");
    $(self.selectedRatingSVGContainer).css('box-shadow', '');
    self.ratingElements = [].slice.call(self.containerElement.querySelectorAll(".rating-option")).map(function (element) {
        return {
            container: element,
            icon: element.querySelector(".icon"),
            label: element.querySelector(".label"),
            selectedFill: self.hexToRGB(element.getAttribute("selected-fill") || "#FFD885")
        };
    });
    if ($('#showlangid').val() == '2' || $('#showlangid').val() == '3') {
        self.ratingElements.reverse();
    }
    // //console.log(self.ratingElements);

    self.selectedRating;
    self.sliderPosition = 0;
    self.facePaths = [];
    self.labelColor = self.hexToRGB("#ABB2B6");
    self.labelSelectedColor = self.hexToRGB("#313B3F");
    self.dragging = false;
    self.handleDragOffset = 0;
    self.ratingTouchStartPosition = { x: 0, y: 0 };
    self.onRatingChange = function (rating) {
        if ($('#showlangid').val() == '2' || $('#showlangid').val() == '3') {
            if (rating == 0) {
                rating = 4;
            }
            else if (rating == 1) {
                rating = 3;
            }
            else if (rating == 2) {
                rating = 2;
            }
            else if (rating == 3) {
                rating = 1;
            }
            else if (rating == 4) {
                rating = 0;
            }
        }
        //  //console.log('onRatingChange--' + rating);
        $(self.selectedRatingSVGContainer).css('box-shadow', '0 3px 5px rgba(0,0,0,0.08)');
        $('.rating-option').removeClass('mactiverating');
        $('.mratingslide_' + rating).addClass('mactiverating');
    };
    self.easings = {
        easeInOutCubic: function (t, b, c, d) {
            if ((t /= d / 2) < 1) return c / 2 * t * t * t + b;
            return c / 2 * ((t -= 2) * t * t + 2) + b;
        },
        easeInOutQuad: function (t, b, c, d) {
            if ((t /= d / 2) < 1) return c / 2 * t * t + b;
            return -c / 2 * ((--t) * (t - 2) - 1) + b;
        },
        linear: function (t, b, c, d) {
            return c * t / d + b;
        }
    };

    self.onHandleDrag = self.onHandleDrag.bind(this);
    self.onHandleRelease = self.onHandleRelease.bind(this);

    self.ratingElements.forEach(function (element) {
        // Copy face path data from HTML
        var paths = {};
        [].forEach.call(element.icon.querySelectorAll("path:not(.base)"), function (path) {
            var pathStr = path.getAttribute("d");
            paths[path.getAttribute("class")] = self.splitString(pathStr);
        });
        self.facePaths.push(paths);
        // On rating selected
        element.container.addEventListener("ontouchend" in document ? "touchend" : "click", function (e) {
            if ("ontouchend" in document) {
				////console.log('On rating touchend');
                var ratingTouchCurrentPosition = { x: e.pageX, y: e.pageY };
                var dragDistance = Math.sqrt(Math.pow(ratingTouchCurrentPosition.x - self.ratingTouchStartPosition.x, 2) + Math.pow(ratingTouchCurrentPosition.y - self.ratingTouchStartPosition.y, 2));
				////console.log('dragDistance -- ' + dragDistance);
                //if (dragDistance > 10) {
                    //return;
                //}
            }
            var newRating = element.container.getAttribute("rating") - 1;
            //  //console.log(newRating);
            if ($('#showlangid').val() == '2' || $('#showlangid').val() == '3') {
                if (newRating == 0) {
                    newRating = 4;
                }
                else if (newRating == 1) {
                    newRating = 3;
                }
                else if (newRating == 2) {
                    newRating = 2;
                }
                else if (newRating == 3) {
                    newRating = 1;
                }
                else if (newRating == 4) {
                    newRating = 0;
                }
            }
			////console.log('newRating---'+newRating);
            self.setRating(newRating, { fireChange: true });
        });
    });

    if ("ontouchend" in document) {
        document.body.addEventListener("touchstart", function (e) {
		////console.log('--touchoriginalstart--');
		////console.log(e.target.classList);
		////console.log(e.target.classList.contains("rating-option"));
            if (e.target.classList.contains("rating-option")) {
                self.ratingTouchStartPosition = { x: e.touches[0].pageX, y: e.touches[0].pageY };
				//console.log(self.ratingTouchStartPosition);
            }
        });
		//console.log(self.selectedRatingElement);
        self.selectedRatingElement.addEventListener("touchstart", function (e) {
		//console.log('--touchstart--');
            self.dragging = true;
            self.handleDragOffset = e.touches[0].pageX - self.selectedRatingElement.getBoundingClientRect().left;
            self.setLabelTransitionEnabled(false);
        });
        self.selectedRatingElement.addEventListener("touchmove", self.onHandleDrag);
        self.selectedRatingElement.addEventListener("touchend", self.onHandleRelease);
    } else {
        document.body.addEventListener("mousedown", function (e) {
            if (e.target == self.selectedRatingElement) {
                e.preventDefault();
                self.dragging = true;
                self.handleDragOffset = e.offsetX;
                self.setLabelTransitionEnabled(false);
                document.body.classList.add("dragging");
                document.body.addEventListener("mousemove", self.onHandleDrag);
            }
        });
        document.body.addEventListener("mouseup", function (e) {
            if (self.dragging) {
                document.body.classList.remove("dragging");
                document.body.removeEventListener("mousemove", self.onHandleDrag);
                self.onHandleRelease(e);
            }
        });
    }
    //if(msetrating!=null || msetrating!=-1||msetrating!=)
    //self.setRating(3, { duration: 0 });
}


RatingControl.prototype = {
    setRating: function (rating, options) {
         //console.log('hahaha' + rating);
        var self = this;
        var options = options || {};
        var startTime;
        var fireChange = options.fireChange || false;
        var onComplete = options.onComplete || function () { };
        var easing = options.easing || self.easings.easeInOutCubic;
        var duration = options.duration == undefined ? 550 : options.duration;
        var startXPosition = self.sliderPosition;
        var endXPosition = rating * self.selectedRatingElement.offsetWidth;

         ////console.log('duration' + duration);
        if (duration > 0) {
            var anim = function (timestamp) {
				////console.log('startTime' + startTime);
				////console.log('timestamp' + timestamp);
                startTime = startTime || timestamp;
                var elapsed = timestamp - startTime;
                var progress = easing(elapsed, startXPosition, endXPosition - startXPosition, duration);
				////console.log('elapsed' + elapsed);
				//console.log('progress' + progress);
                self.setSliderPosition(progress);
                if (elapsed < duration) {
                    requestAnimationFrame(anim);
                } else {
					//console.log('endXPosition--' + endXPosition);
                    self.setSliderPosition(endXPosition);
                    self.setLabelTransitionEnabled(true);
                    if (self.onRatingChange && self.selectedRating != rating && fireChange) {
							//console.log('onRatingChange--' + rating);
                        self.onRatingChange(rating);
                    }
                    onComplete();
                    self.selectedRating = rating;
                }
            };

            self.setLabelTransitionEnabled(false);
            requestAnimationFrame(anim);
        } else {
			////console.log('no duration' + endXPosition);
            self.setSliderPosition(endXPosition);
            if (self.onRatingChange && self.selectedRating != rating && fireChange) {
                self.onRatingChange(rating);
            }
            onComplete();
            self.selectedRating = rating;
        }
    },

    setSliderPosition: function (position) {
        var self = this;
        ////console.log('position--' + position);
        self.sliderPosition = Math.min(Math.max(0, position), self.containerElement.offsetWidth - self.selectedRatingElement.offsetWidth);
        var stepProgress = self.sliderPosition / self.containerElement.offsetWidth * self.ratingElements.length;
        var relativeStepProgress = stepProgress - Math.floor(stepProgress);
        var currentStep = Math.round(stepProgress);
        var startStep = Math.floor(stepProgress);
        var endStep = Math.ceil(stepProgress);
        // Move handle
		////console.log('self.selectedRatingElement.style--'+self.selectedRatingElement.style);
		////console.log('trandofrm--'+self.selectedRatingElement.style.transform);
		$(self.selectedRatingElement).css('-webkit-transform', "translateX(" + (self.sliderPosition / self.selectedRatingElement.offsetWidth * 100) + "%)");
        self.selectedRatingElement.style.transform = "translateX(" + (self.sliderPosition / self.selectedRatingElement.offsetWidth * 100) + "%)";
        // Set face
        var startPaths = self.facePaths[startStep];
        var endPaths = self.facePaths[endStep];
        var interpolatedPaths = {};
        
        ////console.log('endStep--'+endStep);
        ////console.log('-startPaths-'+startPaths.Length);
        for (var featurePath in startPaths) {
            // //console.log(featurePath);
            if (startPaths.hasOwnProperty(featurePath)) {
                var startPath = startPaths[featurePath];
                if (endPaths != undefined) {
                    var endPath = endPaths[featurePath];
                    var interpolatedPoints = self.interpolatedArray(startPath.digits, endPath.digits, relativeStepProgress);
                    var interpolatedPath = self.recomposeString(interpolatedPoints, startPath.nondigits);
                    interpolatedPaths[featurePath] = interpolatedPath;
                }
                else {
                    ////console.log('startPath--' + startStep);
                    ////console.log('endPath--' + endStep);
                }
            }
        }
        // //console.log(self.ratingElements);
        // //console.log(startStep + '_' + endStep + '_' + relativeStepProgress);
        if (endStep < 5) {
            var interpolatedFill = self.interpolatedColor(self.ratingElements[startStep]["selectedFill"], self.ratingElements[endStep]["selectedFill"], relativeStepProgress);
            // //console.log(interpolatedFill);
            self.selectedRatingSVGContainer.innerHTML = '<svg width="55px" height="55px" viewBox="0 0 50 50"><path d="M50,25 C50,38.807 38.807,50 25,50 C11.193,50 0,38.807 0,25 C0,11.193 11.193,0 25,0 C38.807,0 50,11.193 50,25" class="base" fill="' + interpolatedFill + '"></path><path d="' + interpolatedPaths["mouth"] + '" class="mouth" fill="#655F52"></path><path d="' + interpolatedPaths["right-eye"] + '" class="right-eye" fill="#655F52"></path><path d="' + interpolatedPaths["left-eye"] + '" class="left-eye" fill="#655F52"></path></svg>';
        }
        //self.selectedRatingElement.attr('');
        ////console.log('position---' + position);
        // Update marker icon/label
        self.ratingElements.forEach(function (element, index) {
            var adjustedProgress = 1;
            if (index == currentStep) {
                adjustedProgress = 1 - Math.abs((stepProgress - Math.floor(stepProgress) - 0.5) * 2);
            }
			////console.log('adjustedProgress---' + adjustedProgress);
            element.icon.style.transform = "scale(" + adjustedProgress + ")";
            element.label.style.transform = "translateY(" + self.interpolatedValue(9, 0, adjustedProgress) + "px)";
            element.label.style.color = self.interpolatedColor(self.labelSelectedColor, self.labelColor, adjustedProgress);
        });
    },

    onHandleDrag: function (e) {
		//console.log('--onHandleDrag--');
        var self = this;
        e.preventDefault();
        if (e.touches) {
            e = e.touches[0];
        }
        var offset = self.selectedRatingElement.offsetWidth / 2 - self.handleDragOffset;
        var xPos = e.clientX - self.containerElement.getBoundingClientRect().left;
        self.setSliderPosition(xPos - self.selectedRatingElement.offsetWidth / 2 + offset);
    },

    onHandleRelease: function (e) {
		//console.log('--onHandleRelease--');
        var self = this;
        self.dragging = false;
        self.setLabelTransitionEnabled(true);
        var rating = Math.round(self.sliderPosition / self.containerElement.offsetWidth * self.ratingElements.length);
        //console.log('--'+rating);
        //if ($('#showlangid').val() == '2' || $('#showlangid').val() == '3') {
        //    if (rating == 0) {
        //        rating = 4;
        //    }
        //    else if (rating == 1) {
        //        rating = 3;
        //    }
        //    else if (rating == 2) {
        //        rating = 2;
        //    }
        //    else if (rating == 3) {
        //        rating = 1;
        //    }
        //    else if (rating == 4) {
        //        rating = 0;
        //    }
        //}
        self.setRating(rating, { duration: 200, fireChange: true });
    },

    setLabelTransitionEnabled: function (enabled) {
        var self = this;
        self.ratingElements.forEach(function (element) {
            if (enabled) {
                element.label.classList.remove("no-transition");
            } else {
                element.label.classList.add("no-transition");
            }
        });
    },

    interpolatedValue: function (startValue, endValue, progress) {
        return (endValue - startValue) * progress + startValue;
    },

    interpolatedArray: function (startArray, endArray, progress) {
        return startArray.map(function (startValue, index) {
            return (endArray[index] - startValue) * progress + startValue;
        });
    },

    interpolatedColor: function (startColor, endColor, progress) {
        var self = this;
        var interpolatedRGB = self.interpolatedArray(startColor, endColor, progress).map(function (channel) {
            return Math.round(channel);
        });
        return "rgba(" + interpolatedRGB[0] + "," + interpolatedRGB[1] + "," + interpolatedRGB[2] + ",1)";
    },

    easeInQuint: function (t, b, c, d) {
        return c * (t /= d) * t * t + b;
    },

    hexToRGB: function (hex) {
        // Expand shorthand form to full form
        var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
        hex = hex.replace(shorthandRegex, function (m, r, g, b) {
            return r + r + g + g + b + b;
        });
        var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? [
          parseInt(result[1], 16),
          parseInt(result[2], 16),
          parseInt(result[3], 16)
        ] : null;
    },

    splitString: function (value) {
        var re = /-?\d*\.?\d+/g;
        var toStr = function toStr(val) {
            return typeof val == "string" ? val : String(val);
        };
        return {
            digits: toStr(value).match(re).map(Number),
            nondigits: toStr(value).split(re)
        };
    },

    recomposeString: function (digits, nondigits) {
        return nondigits.reduce(function (a, b, i) {
            return a + digits[i - 1] + b;
        });
    },

    simulateRatingTap: function (rating, delay, complete) {
		//console.log('simulateRatingTap');
        var self = this;
        var ratingElement = self.ratingElements[rating];
        setTimeout(function () {
            ratingElement.container.classList.add("show-touch");
            setTimeout(function () {
                ratingElement.container.classList.remove("show-touch");
                self.setRating(rating, {
                    onComplete: function () {
                        if (complete) {
                            complete();
                        }
                    }
                });
            }, 250);
        }, delay || 0);
    },

    simulateRatingDrag: function (rating, delay, complete) {
        var self = this;
        setTimeout(function () {
            self.selectedRatingElement.classList.add("show-touch");
            setTimeout(function () {
                self.setRating(rating, {
                    duration: 3000,
                    easing: self.easings.easeInOutQuad,
                    onComplete: function () {
                        self.selectedRatingElement.classList.remove("show-touch");
                        if (complete) {
                            complete();
                            //  self.selectedRatingElement.attr('');
                        }
                    }
                });
            }, 250);
        }, delay || 0);
    }
}

这是一个计分页面,如何将其发送到WebView?

0 个答案:

没有答案