大家好,在這裡和大家分享我剛剛學到的知識:通過Intent開啟網頁
首先,開啟布局檔案中main.xml,建立為LinearLayout布局,並且建立一個EditText和Button控制項。具體代碼如下:
<?xml version="1.0" encoding="utf-8"?><br /><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"<br /> android:orientation="horizontal"<br /> android:layout_width="fill_parent"<br /> android:layout_height="fill_parent"<br /> ><br /><EditText<br />android:id = "@+id/editText"<br />android:layout_width="wrap_content"<br />android:layout_height="wrap_content"<br />android:layout_weight="1.0"<br />android:lines="1"<br />/><br /><Button<br />android:id = "@+id/button1"<br />android:layout_width="wrap_content"<br />android:layout_height="wrap_content"<br />android:text = "go"<br />/><br /></LinearLayout><br />
效果
package org.exmaple.MyBrowserIntent;<br />import android.app.Activity;<br />import android.content.Intent;<br />import android.net.Uri;<br />import android.os.Bundle;<br />import android.view.KeyEvent;<br />import android.view.View;<br />import android.view.View.OnClickListener;<br />import android.view.View.OnKeyListener;<br />import android.widget.Button;<br />import android.widget.EditText;<br />public class MyBrowserIntent extends Activity {</p><p>private EditText editText;<br />private Button goButton;</p><p> /** Called when the activity is first created. */<br /> @Override<br /> public void onCreate(Bundle savedInstanceState) {<br /> super.onCreate(savedInstanceState);<br /> setContentView(R.layout.main);</p><p> editText = (EditText) indViewById(R.id.editText);<br /> goButton = (Button) indViewById(R.id.button1);</p><p> editText.setOnKeyListener(new OnKeyListener() {<br /> //按鈕鍵盤點擊事件<br />@Override<br />public boolean onKey(View arg0, int arg1, KeyEvent arg2) {<br />// TODO Auto-generated method stub<br />if(arg1 == KeyEvent.KEYCODE_ENTER) {<br />//使用者按了Enter則調用openBrowser()方法<br />openBrowser();<br />return true;<br />}<br />return false;<br />}</p><p> });<br /> goButton.setOnClickListener(new OnClickListener(){ //按鈕綁定點擊事件<br />@Override<br />public void onClick(View v) {<br />// TODO Auto-generated method stub<br />openBrowser();<br />}<br /> });<br /> }<br />protected void openBrowser() {<br />// TODO Auto-generated method stub<br />Uri uri = Uri.parse("http://"+editText.getText().toString());<br />//通過Uri獲得編輯框裡的//地址,加上http://是為了使用者輸入時可以不要輸入<br />Intent intent = new Intent(Intent.ACTION_VIEW,uri);<br />//建立Intent對象,傳入uri<br />startActivity(intent);<br />//啟動<br />}<br />}
到這裡就一切OK啦!
哈哈!看下:
輸入www.google.com
這是本人第一次寫部落格,有不足的地方請大家指正,還請大家多多關注我的部落格,我會和大家分享我的學習成果的!