歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android學習筆記之自制簡易浏覽器

Android學習筆記之自制簡易浏覽器

日期:2017/3/1 9:55:59   编辑:Linux編程

首先,不要題目嚇到——這個簡易浏覽器真得很簡易!我們的任務就是——輸入網址,然後顯示出對應的頁面。但是通過這個簡易例子,今天來介紹下一個新的組件:WebView。

表面上來看,這個WebView組件似乎與普通ImageView還差不多,但實際上這個組件的功能要強大得多,WebView本身就是一個浏覽器實現(所以說任務很簡易嘛...),它的內核基於WebKit引擎(一個開源項目,Android系統自帶的浏覽器就是基於它實現的)。

功能強大歸強大,WebView的用法卻一點也不復雜,與普通ImageView的用法基本相似。重要的是,它提供了一系列的方法來執行浏覽器操作,下面是幾個常用的方法:

  • void goBack():後退
  • void goForward():前進
  • void loadUrl(String url):加載指定URL對應的網頁
  • boolean zoomIn():放大網頁
  • boolean zoomOut():縮小網頁

為了完成今天的這個自制簡易浏覽器程序,我們首先就需要在布局文件中定義一個WebView組件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<EditText
android:id="@+id/url"
android:inputType="textUri"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<WebView
android:id="@+id/show"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

然後,就需要在Activity程序中獲取EditText文本框中輸入的組件,然後在WebView中將對應的網頁顯示出來:

public class MainActivity extends Activity
{
private EditText url=null;
private WebView show=null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_main);
this.url=(EditText)super.findViewById(R.id.url);
this.show=(WebView)super.findViewById(R.id.show);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_SEARCH)
{
String urlStr=this.url.getText().toString();
//加載並顯示url對應的網頁
this.show.loadUrl(urlStr);
return true;
}
return false;
}

}

運行改程序,可能的結果是顯示無法打開網頁,這時就應該反射性地想到是不是忘了下一步:

在AndroidManifest.xml文件中添加權限:

<uses-permission
android:name="android.permission.INTERNET" />

到此,一個簡易的自制浏覽器就完成了......

當然,這個簡易浏覽器還有許多可以改進的地方,可以增加些使用功能,或是美化下程序界面,然後你就可以使用自制的浏覽器代替android系統浏覽器了!

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved