您的位置:首页 > 移动开发 > Android开发

Android之使用Intent跳转到一个网页

2014-12-10 22:32 411 查看
1.首先,建立一个安卓项目,项目名为IntentTest,创建完成后,打开res目录下的layout文件夹的activity_main.xml文件,进行布局,代码附上:

activity_main.xml文件:

<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">
    
    <EditText 
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textUri"
        android:text="http://www.baidu.com/"/>
    
    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="跳转网页"/>
    
</LinearLayout>

布局文件下有两个控件,一个编辑框,一个按钮,点击按钮跳转到编辑框里面的uri地址。

2.接下来,对src目录下的包里面的MainActivity.java文件打开, 修改里面的代码,代码附上:

MainActivity.java文件:

package com.example.intenttest;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

	private Button button1;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);//设置页面布局
		button1=(Button)findViewById(R.id.button1);//获取按钮控件
		
		button1.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				EditText editText1=(EditText)findViewById(R.id.editText1);//获得编辑框控件
				Intent intent=new Intent();//创建Intent对象
				intent.setAction(Intent.ACTION_VIEW);//为Intent设置动作
				String data=editText1.getText().toString();//获取编辑框里面的文本内容
				intent.setData(Uri.parse(data));//为Intent设置数据
				startActivity(intent);//将Intent传递给Activity
			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}


3.这样就可以用Intent跳转到一个网页了,接下来运行此项目,运行效果如下:



在布局文件里我默认把编辑框的文本内容设置为百度的网址,接下来点击跳转网页的按钮,效果如下,其中必须保证你的计算机有网络:



这样就浏览到百度的网页了。

4.以上就是如何利用Intent浏览访问一个网页,很简单,仅供大家学习参考,写得不好,请见谅,如果有错误请指出,谢谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: