让我们开始用一个web应用开始我们的Android之旅~ 逐步了解如何创建一个应用。

开始构建一个webkit程序

最简单的构建一个程序就不说了,见文末附录参考文章。

一个Webview程序有几个问题:
1 需要允许访问互联网
2 捕获链接点击,不能让系统接手用浏览器打开新链接
3 重定义返回键,防止返回就回到桌面了

代码(本示例从Sample文件里的WebView1.java为母版修改):
[android-sdk-windows-1.5_r2\platforms\android-1.5\samples\ApiDemos\src\com\example\android\apis\view]

package com.example.android.apis.view;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class WebView1 extends Activity {
  private WebView wv;
    private String init_url = "http://www.aslibra.com/android/";
    
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);      
        setContentView(R.layout.main);
        
        wv = (WebView) findViewById(R.id.wv1);
        //允许运行脚本
        wv.getSettings().setJavaScriptEnabled(true);
        //捕获链接点击
        wv.setWebViewClient(new WebViewClient(){  
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
              //捕获网址,以后也许可以根据锚链接处理点互动
              show_msg(url);
              view.loadUrl(url);  
                return true;
            }
        });  
        wv.loadUrl(init_url);
    }

    public void show_msg(String msg){
      new AlertDialog.Builder(this)
      .setTitle("提示:有链接点击")
      .setMessage(msg)
        /*.setPositiveButton("确定", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
        })
        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
        }
        })*/
        .show();      
    }
    
    //防止点击链接后按返回直接回到桌面
    public boolean onKeyDown(int keyCode, KeyEvent event) {  
        if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {  
            wv.goBack();  
            return true;  
        }  
        return super.onKeyDown(keyCode, event);  
    }
}


参考文章:
1 示例程序:Hello, WebView
2 WebView初探


原创内容如转载请注明:来自 阿权的书房
收藏本文到网摘
Tags:
发表评论
表情
emotemotemotemotemotemotemotemotemotemotemotemotemot
emotemotemotemotemotemotemotemotemotemotemotemot
打开HTML 打开UBB 打开表情 隐藏
昵称   密码   游客无需密码
网址   电邮   [注册]
               

验证码 不区分大小写
 

阅读推荐

服务器相关推荐

开发相关推荐

应用软件推荐