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 cordova-plugin-camera@2.4.1
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

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cordova简介 【http://cordova.apache.org/docs/en/latest/guide/overview/】 Cordova是一个开源的移动终端开发框架,它提供使用html,css,javascript 技术进行跨平台开发能力,并且封装了一组javascript接口实现访问摄像头,地理定位,存储,网络状态等移动终端的硬件属性。 Android开发平台配置步骤 1. Jdk安装配置。 安装jdk1.7。 配置jdk的系统变量。 添加JAVA_HOME变量: C:\Program Files\Java\jdk1.7.0_79 添加CLASSPATH变量: .;%JAVA_HOME%\lib;%JAVA_HOME%\lib\tools.jar Path变量 里面添加内容: %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; 2.adroid sdk安装配置。 1)安装sdk, http://www.cnblogs.com/bjzhanghao/archive/2012/11/14/android-platform-sdk-download-mirror.html 2)配置变量 添加ANDROID_SDK_HOME变量: C:\Program Files (x86)\Android\android-sdk Path变量 里面添加内容: %ANDROID_SDK_HOME%\platform-tools;%ANDROID_SDK_HOME%\\tools; 3)下载 Android -API: 打开android sdk manager 窗口下载anroid 6 和android 5.0 api。 下载失败解决方法,在android sdk manager 界面tools菜单 ->options 窗口,进行如下设置: http proxy server :mirrors.opencas.cn; http proxy port :80; 选项框选中 force https://..sources to fetched using http://...; 3.eclipse安装配置。 1)下载eclipse工具。 2)下载安装adt插件。http://dl.google.com/android/ADT-21.0.0.zip 在eclipse界面的help菜单-》install new software,打开安装窗口,点击add按钮,弹出add repository窗口,点击archive按钮,选中 ADT-21.0.0.zip文件,完成安装。 Android开发模式 打开eclipse导入工程,在MainActivity项目里打开assets\www目录,里面就是相关就是有个WEB开发的相关文件,可以添加js,css,html完成相关业务功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值