ionic升华过程8-cordova插件+mui小案例

一。mui简介。

   MUI是一套前端框架,由DCLOUD公司研发而成,提供大量H5和js语言组成的组件,大大提高了开发效率,可以用于开发web端应用、web app等应用,中国比较流行的前端工具Hbuilder也是出自该公司 Hbuilder中集成mui。hbuilder提供了代码库提示功能非常强大 官方演示(http://dev.dcloud.net.cn/mui/snippet/):

mui官方文档提供了很多ui控件 (自称最接近原生app 文档比较粗糙)地址:http://dev.dcloud.net.cn/mui/ui/
控件自学

二 。案例演示。

制作一个简单的 火山小视频的demo 实现一个上滑刷新获取数据 点击右上角视频 调用系统摄像头功能(cordova) 效果图如下

使用cordova创建一个项目

C:\Users\Administrator>cordova create hello1 cn.hello1 hello1
Creating a new cordova project.

使用hbuilder打开目录 打开项目  项目上右键 转换成移动app

在hbuilder新建一个移动项目  将 css和fonts和js中的文件拷贝到www对应目录

如果是使用vscode开发 
vscode安装 cordovatools 打开调试窗口 点击配置打开lauanch.json 列表很多选项 

Run Android on Devide 当手机插入 可以安装到手机设备
Run Android on emulator 运行程序在模拟器上
simulate Android on Browser 在浏览器上模拟android 

页面绘制 就不谈 直接给出源代码 
home.html(首页的子页面)

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>

	<head>
		<!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
-->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;script-src * 'unsafe-inline'">-->
		<meta name="format-detection" content="telephone=no">
		<meta name="msapplication-tap-highlight" content="no" charset="utf-8">
		<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

		<script src="js/mui.min.js"></script>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="css/index.css">
		<script type="text/javascript" charset="utf-8">
			mui.init({
				pullRefresh: {
					container: "#refreshContainer", //下拉刷新容器标识,querySelector能定位的css选择器均可,比如:id、.class等
					up: {
						height: 50, //可选,默认50.触发下拉刷新拖动距离,
						auto: false, //可选,默认false.首次加载自动下拉刷新一次
						contentrefresh: "正在刷新...", //可选,正在刷新状态时,下拉刷新控件上显示的标题内容
						contentnomore:'没有更多数据了',//可选,请求完毕若没有更多数据时显示的提醒内容; 
						callback: function() {
							var rthis=this;
							query(function(data){
								if(data.length==0){
									//没有数据了 不能拉了
									rthis.endPullupToRefresh(true);
								}
								//数据加载完成将正在加载去掉 false表示还有数据可以继续拉
								rthis.endPullupToRefresh(false);
							});
							//mui('#refreshContainer').pullRefresh().refresh(true);
							 //this.endPullupToRefresh(true); 没有数据了 就调用这个函数
						} //必选,刷新函数,根据具体业务来编写,比如通过ajax从服务器获取新数据;
					}
				}
			});
			var requestServer="http://192.168.1.3:8888/";
			var start=0;
			var length=6;
			function query(fn){
				mui.ajax({
					url:requestServer+"list?start="+start+"&length="+length,
					crossDomain:true,
					dataType:'json',
					success:function(data){
						console.log(JSON.stringify(data));
						mui.each(data,function(index,item){
							if(index % 2!=0 ){
								return;
							}
							var imgPath=requestServer+"view?fileName=";
							var headerHtml="<div id='r_"+index+"' class='mui-row'>";
							var firstImage="<div id='r_"+index+"_c_0' class='mui-col-sm-6 mui-col-xs-6'>"+
							"	<li class='mui-table-view-cell imageView' style='background-image: url("+(imgPath+item.imageUrl)+");background-size: cover;'>"+
							"	<div style='font-size:15px;font-weight:bold;color:white;padding-bottom:180px;width:150%'>"+item.showTitle+"</div> "+
							"</li>"+
							"</div>";
							var secondImage="";
							if((index+1)<data.length){
								secondImage="<div id='r_"+index+"_c_1' class='mui-col-sm-6 mui-col-xs-6' >"+
								"	<li class='mui-table-view-cell imageView' style='background-image: url("+(imgPath+data[index+1].imageUrl)+");background-size: cover;'>"+
								"	<div style='font-size:15px;font-weight:bold;color:white;padding-top:180px;width:150%'>"+data[index+1].showTitle+"</div> "+
								"	</li>"+
								"</div>";
							}
						   var footHtml="</div>";
						   var newEle=headerHtml+firstImage+secondImage+footHtml;
						   mui("#contentView")[0].innerHTML=mui("#contentView")[0].innerHTML+newEle;
						   //var firstRowElement=mui("#r_"+index);
						   /*
						   var firstColElement=mui("#r_"+index+"_c_0")[0];
						   //算出第一个div显示文字的文字 行离圆点的高度-20
						   var showTop=firstColElement.offsetTop+firstColElement.offsetHeight/12*11;
						   //离左侧的距离 div离左侧的距离+跨度的 1/5
						   var showLeft=firstColElement.offsetLeft+firstColElement.offsetWidth/20;
						   //debugger
						   var showDiv=document.createElement("div");
						   console.log(item.showTitle);
						   showDiv.innerHTML=item.showTitle;
						   //showDiv.style.backgroundColor="red";
						   //showDiv.style.borderStyle="1px solid green";
						   showDiv.style.position="absolute";
						   showDiv.style.fontWeight="bold";
						   showDiv.style.fontSize="15px";
						   showDiv.style.color="white";
						   console.log("#r_"+index+"_c_0"+showLeft+"----"+showTop);
						   
						   showDiv.style.left=showLeft+"px";
						   showDiv.style.top=showTop+"px";
						  
						   
						   showDiv.style.zIndex=100;
						    document.body.appendChild(showDiv);
						    **/
						})
						start+=6;
						if(fn)
							fn(data);
					}
				})
			}
			//初始化事件
			mui(function(){
				query();
				document.addEventListener("deviceready", onDeviceReady, false);
				function onDeviceReady() {
				    console.log(navigator.camera);
				    alert("chushihua");
				}
				//监听点击事件
				mui("#camera")[0].addEventListener("tap",function(){
					alert("ggg");
				});
			})
		</script>
		<title>Hello World</title>
	</head>
 
	<body>
		<header class="mui-bar mui-bar-nav">
			<!--mui-row表示一行 MUI里面也是使用的十二列的栅格系统。  mui-cos-xs-11佔用11格-->
			<div class="mui-row">
				<div class="mui-col-xs-2">
					<span class="mui-icon mui-icon-search"></span>

				</div>
				<div class="mui-col-xs-9">
					<div class="mui-row">
						<div class="mui-col-xs-4">
							<span class="mui-icon">视频 </span>

						</div>
						<div class="mui-col-xs-4">
							<span class="mui-icon">直播</span>

						</div>
						<div class="mui-col-xs-4">
							<span class="mui-icon">同城</span>

						</div>
					</div>
				</div>

				<div class="mui-col-xs-1">
					<span id="camera" class="mui-icon mui-icon-camera"></span>
				</div>
			</div>

		</header>

		<div class="mui-content" >

			!--下拉刷新容器-->
			<div id="refreshContainer" class="mui-content mui-scroll-wrapper" style="margin-top: 40px;">
				<div class="mui-scroll">
					<!--数据列表-->
					<ul id="contentView" class="mui-table-view mui-table-view-chevron">

						
						
					</ul>
				</div>
			</div>
		</div>

		
	</body>

</html>

index.html(工具栏 包含home.html)

<!DOCTYPE html>
<!--
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
     KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
-->
<html>

	<head>
		<!--
        Customize this policy to fit your own app's needs. For more guidance, see:
            https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
        Some notes:
            * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
            * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
            * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
                * Enable inline JS: add 'unsafe-inline' to default-src
        -->
		<!--<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">
-->
		<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *;script-src * 'unsafe-inline'">
		<meta name="format-detection" content="telephone=no">
		<meta name="msapplication-tap-highlight" content="no" charset="utf-8">
		<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">

		<script src="js/mui.min.js"></script>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link rel="stylesheet" type="text/css" href="css/index.css">
		<script type="text/javascript" charset="utf-8">
			mui.init({
			    subpages:[{
			      url:"home.html",//子页面HTML地址,支持本地地址和网络地址
			      id:"myHome",//子页面标志
			      styles:{
			        top:'0px',//离顶部距离
        			bottom:'0px',//默认为0px,可不定义;
			        width:"100%",
			        height:"100%"
			      },
			      extras:{}//额外扩展参数
			    }]
			  });
		</script>
		<title>Hello World</title>
	</head>

	<body>
		
		<nav class="mui-bar mui-bar-tab">
			<a class="mui-tab-item mui-active">
				<span class="mui-icon mui-icon-home"></span>
				<span class="mui-tab-label">首页</span>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon mui-icon-personadd"></span>
				<span class="mui-tab-label">关注</span>
			</a>
			<a class="mui-tab-item" >
				<button type="button" style="margin-bottom: 10px;" class="mui-btn mui-btn-danger">+</button>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon-email"></span>
				<span class="mui-tab-label">消息</span>
			</a>
			<a class="mui-tab-item">
				<span class="mui-icon mui-icon-contact"></span>
				<span class="mui-tab-label">我的</span>
			</a>
		</nav>
	</body>

</html>

服务器使用springboot项目 
主类

package cn.et;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@SpringBootApplication
public class Example {

    @RequestMapping("/")
    String home() {
    	String url="https://restapi.amap.com/v3/weather/weatherInfo?city=440300&key=bab4c7212a804ba4abdca01fcbe55ae4";
    	String returnCode=restTemplate.getForEntity(url, String.class).getBody();
        return returnCode;
    }
    @Autowired
    RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
    	return new RestTemplate();
    }
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Example.class, args);
    }

}

控制层 

package cn.et;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class PlayController {
	/**
	 * 测试数据
	 */
	static List<Player> playerList=new ArrayList();
	static {
		playerList.add(new Player("1","1.mp4","1.jpg","花丛中一朵野花 飘出好漂亮的蓝色啊"));
		playerList.add(new Player("2","1.mp4","2.jpg","美女就是腿长长"));
		playerList.add(new Player("3","1.mp4","3.jpg","第一次出现这么漂亮的豪车"));
		playerList.add(new Player("4","1.mp4","4.jpg","蜡笔小新的小屁屁 	"));
		playerList.add(new Player("5","1.mp4","5.jpg","明信片就应该这么写"));
		playerList.add(new Player("6","1.mp4","7.jpg","南瓜排队莱罗"));
		playerList.add(new Player("7","1.mp4","8.jpg","意思意思啊 。。。"));
		playerList.add(new Player("8","1.mp4","9.jpg","中国镇压么真强大啊"));
	}
	 public static void main(String[] args) {
		
	}
	 @ResponseBody
	 @RequestMapping("/list")
	 List<Player> home(Integer start,Integer length) {
		 int endIndex=start+length;
		 if(start>=playerList.size()) {
			 return new ArrayList<Player>();
		 }
		 if(playerList.size()<endIndex) {
			 endIndex=playerList.size();
		 }
		 return playerList.subList(start, endIndex);
     }
	 @RequestMapping("/view")
	 public void write(String fileName,HttpServletResponse response) throws IOException {
		InputStream is=this.getClass().getResourceAsStream("/myplayer/"+fileName);
		FileCopyUtils.copy(is, response.getOutputStream());
		is.close();
		response.flushBuffer();
	 }
	 
	 
	 
	 
}

实体类
 

package cn.et;

public class Player {
	private String playerId;
	private String playerUrl;
	private String imageUrl;
	private String showTitle;
	
	public Player(String playerId, String playerUrl, String imageUrl,String showTitle) {
		super();
		this.playerId = playerId;
		this.playerUrl = playerUrl;
		this.imageUrl = imageUrl;
		this.showTitle=showTitle;
	}
	public String getPlayerId() {
		return playerId;
	}
	public void setPlayerId(String playerId) {
		this.playerId = playerId;
	}
	public String getPlayerUrl() {
		return playerUrl;
	}
	public void setPlayerUrl(String playerUrl) {
		this.playerUrl = playerUrl;
	}
	public String getImageUrl() {
		return imageUrl;
	}
	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}
	public String getShowTitle() {
		return showTitle;
	}
	public void setShowTitle(String showTitle) {
		this.showTitle = showTitle;
	}
	
	
}

添加允许跨域的控制类

package cn.et;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
	public void addCorsMappings(CorsRegistry registry) {  
        registry.addMapping("/**")  
                .allowedOrigins("*")  
                .allowCredentials(true)  
                .allowedMethods("GET", "POST", "DELETE", "PUT")  
                .maxAge(3600);  
    }

}

home.html启动时 发送ajax到 /list 显示列表 /view获取图片 具体读取的图片 在项目src/main/resources/mplayer

关于点击右侧图标 调用摄像头的部分 使用命令 添加cordova的camera插件

C:\Users\Administrator\hello>cordova plugin add cordova-plugin-camera
Unmet project requirements for latest version of cordova-plugin-camera:
    cordova-android (5.2.2 in project, >=6.3.0 required)
Fetching highest version of cordova-plugin-camera that this project supports: 2.4.1 (latest is 4.0.3)
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-compat" for android
Adding cordova-plugin-camera to package.json
Saved plugin info for "cordova-plugin-camera" to config.xml

因为是使用的android5.2.2 默认下载插件都是最新版本的 该项目只支持 2.4.1 下载2.4.1

C:\Users\Administrator\hello>cordova plugin add [email protected]
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-compat" for android
Adding cordova-plugin-camera to package.json
Saved plugin info for "cordova-plugin-camera" to config.xml

使用cordova build android直接报错

A problem occurred configuring root project 'android'.
> Could not resolve all dependencies for configuration ':_debugCompile'.
   > Could not find any version that matches com.android.support:support-v4:24.1.1+.
     Versions that do not match:
         26.1.0
         25.2.0
     Searched in the following locations:
         https://repo1.maven.org/maven2/com/android/support/support-v4/maven-metadata.xml
         https://repo1.maven.org/maven2/com/android/support/support-v4/
         https://jcenter.bintray.com/com/android/support/support-v4/maven-metadata.xml
     Required by:
         :android:unspecified

缺少android支持库 android.support
android sdk的extras找到 所有android.support相关的库 安装


安装完成就可以使用了  具体该插件怎么使用 参考官方文档 我这 因为没有手机测试 以后再补
http://cordova.axuer.com/docs/zh-cn/latest/reference/cordova-plugin-camera/index.html

猜你喜欢

转载自blog.csdn.net/liaomin416100569/article/details/82759622