您当前的位置:首页 > 互联网教程

如何利用html5开发android界面

发布时间:2025-05-19 02:11:37    发布人:远客网络

如何利用html5开发android界面

一、如何利用html5开发android界面

三种解决方式:1 viewport属性 2 CSS控制 3 JS控制

1 viewport属性放在HTML的<meta>中

<SPAN style="FONT-SIZE: x-small"><head>

<title>Exmaple</title>

<meta name=”viewport” content=”width=device-width,user-scalable=no”/>

<SPAN style="FONT-SIZE: x-small"><meta name="viewport"

height= [pixel_value| device-height],

width= [pixel_value| device-width ],

target-densitydpi= [dpi_value| device-dpi|

high-dpi| medium-dpi| low-dpi]

为每种密度创建独立的样式表(注意其中的webkit-device-pixel-ratio 3个数值对应3种分辨率)

<link rel="stylesheet" media="screen and(-webkit-device-pixel-ratio: 1.5)" href="hdpi.css"/>

<link rel="stylesheet" media="screen and(-webkit-device-pixel-ratio: 1.0)" href="mdpi.css"/>

<link rel="stylesheet" media="screen and(-webkit-device-pixel-ratio: 0.75)" href="ldpi.css"/>

在一个样式表中,指定不同的样式

WebView myWebView=(WebView) findViewById(R.id.webview);

myWebView.setWebViewClient(new MyWebViewClient());

另外出于用户习惯上的考虑需要将WebView表现得更像一个浏览器,也就是需要可以回退历史记录

因此需要覆盖系统的回退键 goBack,goForward可向前向后浏览历史页面

public boolean onKeyDown(int keyCode, KeyEvent event){

if((keyCode== KeyEvent.KEYCODE_BACK)&& myWebView.canGoBack(){

return super.onKeyDown(keyCode, event);

public boolean onJsConfirm(WebView view, String url, String message, final JsResult result){

Builder builder= new Builder(MainActivity.this);

builder.setPositiveButton(android.R.string.ok,

new AlertDialog.OnClickListener(){

public void onClick(DialogInterface dialog, int which){

builder.setNegativeButton(android.R.string.cancel,

new DialogInterface.OnClickListener(){

public void onClick(DialogInterface dialog, int which){

builder.setCancelable(false);

public void onProgressChanged(WebView view, int newProgress){

MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress* 100);

super.onProgressChanged(view, newProgress);

public void onReceivedTitle(WebView view, String title){

MainActivity.this.setTitle(title);

super.onReceivedTitle(view, title);

Js代码: console.log("Hello World");

Log信息: Console: Hello World

在WebChromeClient中实现onConsoleMesaage()回调方法,让其在LogCat中打印信息

WebView myWebView=(WebView) findViewById(R.id.webview);

myWebView.setWebChromeClient(new WebChromeClient(){

public void onConsoleMessage(String message, int lineNumber, String sourceID){

Log.d("MyApplication", message+"-- From line"

WebView myWebView=(WebView) findViewById(R.id.webview);

myWebView.setWebChromeClient(new WebChromeClient(){

public boolean onConsoleMessage(ConsoleMessage cm){

Log.d("MyApplication", cm.message()+"-- From line"

*ConsoleMessage还包括一个 MessageLevel表示控制台传递信息类型。您可以用messageLevel()查询信息级别,以确定信息的严重程度,然后使用适当的Log方法或采取其他适当的措施。

● HTML5本地存储在Android中的应用

HTML5提供了2种客户端存储数据新方法:

sessionStorage针对一个Session的数据存储

<script type="text/javascript">

localStorage.lastname="Smith";

document.write(localStorage.lastname);

<script type="text/javascript">

sessionStorage.lastname="Smith";

document.write(sessionStorage.lastname);

localStorage.setItem(“yarin”,“yangfegnsheng”);

localStorage.getItem(“yarin”);

//获取指定下标的键的名称(如同Array)

//return“fresh”//删除一个键值

localStorage.removeItem(“yarin”);

webSettings.setDatabaseEnabled(true);

String dir= this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();

webSettings.setDatabasePath(dir);

webSettings.setDomStorageEnabled(true);

//扩充数据库的容量(在WebChromeClinet中实现)

public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota,

long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater){

quotaUpdater.updateQuota(estimatedSize* 2);

alert('Databases are not supported by your browser');

var shortName='YARINDB';

var displayName='yarin db';

var maxSize= 100000;// in bytes

YARINDB= openDatabase(shortName, version, displayName, maxSize);

console.log("Invalid database version.");

console.log("Unknown error"+ e+".");

transaction.executeSql('CREATE TABLE IF NOT EXISTS yarin(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL,desc TEXT NOT NULL);', [], nullDataHandler, errorHandler);

//Starter data when page is initialized

var data= ['1','yarin yang','I am yarin'];

transaction.executeSql("INSERT INTO yarin(id, name, desc) VALUES(?,?,?)", [data[0], data[1], data[2]]);

function errorHandler(transaction, error){

// Error is a human-readable string.

console.log('Oops. Error was'+error.message+'(Code'+error.code+')');

console.log("SQL Query Succeeded");

transaction.executeSql("SELECT* FROM yarin;", [], dataSelectHandler, errorHandler);

function dataSelectHandler(transaction, results){

for(var i=0; i<results.rows.length; i++){

var row= results.rows.item(i);

var newFeature= new Object();

newFeature.name= row['name'];

newFeature.decs= row['desc'];

document.getElementByIdx_x_x_x("name").innerHTML="name:"+newFeature.name;

document.getElementByIdx_x_x_x("desc").innerHTML="desc:"+newFeature.decs;

var data= ['fengsheng yang','I am fengsheng'];

transaction.executeSql("UPDATE yarin SET name=?, desc=? WHERE id= 1", [data[0], data[1]]);

transaction.executeSql("DROP TABLE yarin;", [], nullDataHandler, errorHandler);

console.log("Table'page_settings' has been dropped.");

textarea.addEventListener("keyup", function(){

window.localStorage["value"]= this.value;

window.localStorage["time"]= new Date().getTime();

alert("LocalStorage are not supported in this browser.");

● HTML5地理位置服务在Android中的应用

webSettings.setGeolocationEnabled(true);

webSettings.setGeolocationDatabasePath(dir);

//配置权限(同样在WebChromeClient中实现)

public void onGeolocationPermissionsShowPrompt(String origin,

GeolocationPermissions.Callback callback){

callback.invoke(origin, true, false);

super.onGeolocationPermissionsShowPrompt(origin, callback);

HTML5中通过navigator.geolocation对象获取地理位置信息

常用的navigator.geolocation对象有以下三种方法:

navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options)

navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options)

navigator.geolocation.clearWatch(watch_position_id)

其中success_callback_function为成功之后处理的函数,error_callback_function为失败之后返回的处理函数,参数position_options是配置项

navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy:false,maximumAge:1000,timeout:15000});

alert("Your browser does not support HTML5 geoLocation");

二、从事Android开发需要自己买Android设备吗

一般情况下不需要,但是如果你的PC内存低于4G,CPU也不太给力,还是买个便宜的手机,如果PC还可以的话,可以使用android虚拟机进行开发。

你只需要去android官网下载android sdk开发包,里面会自带一个模拟器,但是这里需要注意的是由于"墙"的原因官网访问不了,你可以android studio中文社区下载SDK开发包:

点击SDK Manager去下载自己想要的sdk和模拟器的image

上面的截图就是所有模拟设备的镜像文件,你想要开发什么样的设备就可以选择其中的一个进行下载,里面包含了64位intel, ARM手机,TV, Wear手表等设备的镜像。

下载完成后回到SDK根目录。启动AVD Manager(android虚拟设备管理器)

点击右侧的create进行创建自己想要的设备:

这里有不同的设备,对应不同的分辨率,具体就不再描述细节了,创建好后点击确定

出现上面画面,点击start后就可以了,第一次加载比较耗时,请耐心等待。

三、如何在Android开发中熟练使用五种Toast的特效

Toast用于向用户显示一些帮助/提示。下面我做了5中效果,来说明Toast的强大,定义一个属于你自己的Toast。

Toast.makeText(getApplicationContext(),"默认Toast样式",

toast= Toast.makeText(getApplicationContext(),

"自定义位置Toast", Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER, 0, 0);

toast= Toast.makeText(getApplicationContext(),

"带图片的Toast", Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER, 0, 0);

LinearLayout toastView=(LinearLayout) toast.getView();

ImageView imageCodeProject= new ImageView(getApplicationContext());

imageCodeProject.setImageResource(R.drawable.icon);

toastView.addView(imageCodeProject, 0);

LayoutInflater inflater= getLayoutInflater();

View layout= inflater.inflate(R.layout.custom,

(ViewGroup) findViewById(R.id.llToast));

ImageView image=(ImageView) layout

.findViewById(R.id.tvImageToast);

image.setImageResource(R.drawable.icon);

TextView title=(TextView) layout.findViewById(R.id.tvTitleToast);

TextView text=(TextView) layout.findViewById(R.id.tvTextToast);

text.setText("完全自定义Toast");

toast= new Toast(getApplicationContext());

toast.setGravity(Gravity.RIGHT| Gravity.TOP, 12, 40);

toast.setDuration(Toast.LENGTH_LONG);

import android.view.LayoutInflater;

import android.view.ViewGroup;

import android.view.View.OnClickListener;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.TextView;

public class Main extends Activity implements OnClickListener{

Handler handler= new Handler();

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

findViewById(R.id.btnSimpleToast).setOnClickListener(this);

findViewById(R.id.btnSimpleToastWithCustomPosition).setOnClickListener(

findViewById(R.id.btnSimpleToastWithImage).setOnClickListener(this);

findViewById(R.id.btnCustomToast).setOnClickListener(this);

findViewById(R.id.btnRunToastFromOtherThread).setOnClickListener(this);

Toast.makeText(getApplicationContext(),"我来自其他线程!",

Toast.makeText(getApplicationContext(),"默认Toast样式",

case R.id.btnSimpleToastWithCustomPosition:

toast= Toast.makeText(getApplicationContext(),

"自定义位置Toast", Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER, 0, 0);

case R.id.btnSimpleToastWithImage:

toast= Toast.makeText(getApplicationContext(),

"带图片的Toast", Toast.LENGTH_LONG);

toast.setGravity(Gravity.CENTER, 0, 0);

LinearLayout toastView=(LinearLayout) toast.getView();

ImageView imageCodeProject= new ImageView(getApplicationContext());

imageCodeProject.setImageResource(R.drawable.icon);

toastView.addView(imageCodeProject, 0);

LayoutInflater inflater= getLayoutInflater();

View layout= inflater.inflate(R.layout.custom,

(ViewGroup) findViewById(R.id.llToast));

ImageView image=(ImageView) layout

.findViewById(R.id.tvImageToast);

image.setImageResource(R.drawable.icon);

TextView title=(TextView) layout.findViewById(R.id.tvTitleToast);

TextView text=(TextView) layout.findViewById(R.id.tvTextToast);

text.setText("完全自定义Toast");

toast= new Toast(getApplicationContext());

toast.setGravity(Gravity.RIGHT| Gravity.TOP, 12, 40);

toast.setDuration(Toast.LENGTH_LONG);

case R.id.btnRunToastFromOtherThread:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android=""

android:orientation="vertical" android:layout_width="fill_parent"

android:layout_height="fill_parent" android:padding="5dip" android:gravity="center">

<Button android:layout_height="wrap_content"

android:layout_width="fill_parent" android:id="@+id/btnSimpleToast"

android:text="默认"></Button>

<Button android:layout_height="wrap_content"

android:layout_width="fill_parent" android:text="自定义显示位置"

android:id="@+id/btnSimpleToastWithCustomPosition"></Button>

<Button android:layout_height="wrap_content"

android:layout_width="fill_parent" android:id="@+id/btnSimpleToastWithImage"

android:text="带图片"></Button>

<Button android:layout_height="wrap_content"

android:layout_width="fill_parent" android:text="完全自定义"

android:id="@+id/btnCustomToast"></Button>

<Button android:layout_height="wrap_content"

android:layout_width="fill_parent" android:text="其他线程"

android:id="@+id/btnRunToastFromOtherThread"></Button>

<?xml version="1.0" encoding="utf-8"?>

xmlns:android=""

android:layout_height="wrap_content" android:layout_width="wrap_content"

android:background="#ffffffff" android:orientation="vertical"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

android:background="#bb000000"

android:id="@+id/tvTitleToast"/>

android:layout_height="wrap_content"

android:orientation="vertical"

android:id="@+id/llToastContent"

android:layout_marginLeft="1dip"

android:layout_marginRight="1dip"

android:layout_marginBottom="1dip"

android:layout_width="wrap_content"

android:background="#44000000">

android:layout_height="wrap_content"

android:layout_gravity="center"

android:layout_width="wrap_content"

android:id="@+id/tvImageToast"/>

android:layout_height="wrap_content"

android:layout_width="wrap_content"

android:id="@+id/tvTextToast"/>