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

Android 四大组件 —— 活动(使用Intent 实现活动的显示跳转)

2018-01-18 20:33 696 查看
一、什么是Intent?        Intent的中文意思是目的。在Android中也是“目的”的意思。就是我们要去哪里,从这个activity要前往另一个Activity就需要用到Intent。下面是 Intent 两个最基本的函数:1、定义一个Intent[java] view plain copyIntent intent = new Intent(IntentDemo.this, AnotherActivity2.class);  
2、启动 Activity[java] view plain copystartActivity(intent);  
以上示例代码的作用是从IntentDemo这个activity切换到AnotherActivity2。这是Intent其中一种构造方法,指定两个Activity。为什么需要指定两个活动呢?因为在Android中有一个活动栈,这样的构造方式才能确保正确的将前一个活动压入栈中,才能在触发返回键的时候活动能够正确出栈。     Intent 是Android 程序中各组件之间进行交互的一种重要方式,它不仅可以指明当前组件想要执行的动作,还可以在不同组件之间传递数据。Intent 一般可被用于启动活动、启动服务、以及发送广播等场景. Intent 的用法大致可以分为两种,显式Intent 和隐式Intent,我们先来看一下显式Intent如何使用。二、使用 Intent 实现活动的显示跳转这里我们以按钮实现活动跳转为例,为实现这个功能,我们需要三个步骤:1、拿到按钮对象       如何拿到按钮对象呢?通过资源id,前面我们提到过,在R.id.xxx 中会有我们的资源id,但button按钮是在layout 中创建的,系统不会为其创建资源id,所以我们需要在layout 设置 button 时自己加上id,、,具体方法如下:[java] view plain copy<Button  
       android:id="@+id/button1"  
       android:layout_width="match_parent"  
       android:layout_height="wrap_content"  
       android:text="点我点我!"   
       android:textSize="25sp"/>  
可以看到设置id 的方法是 id = "@+id/button1",这里button1 即我们将使用的资源id。 2、为此按钮设定点击监听事件这样每当点击按钮时,就会执行监听器中的onClick()方法,我们只需要在这个方法中加入待处理的逻辑就行了;具体代码如下:[java] view plain copypublic class MainActivity extends Activity {  
    private Button button;  
      
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        button = (Button) findViewById(R.id.button);  
          
        button.setOnClickListener(new OnClickListener() {  
            @Override  
            public void onClick(View v) {  
            // 在此处添加逻辑  
            }  
        });  
    }  
}  

3、实现跳转      当然这是最重要的一步了,通过Intent 实现,我们先来了解一下Intent 函数;Intent  意图,告诉系统我们要干什么,连接四大组件的纽带,可以启动活动、启动服务、发送广播;公共构造函数:1)、Intent() 空构造函数2)、Intent(Intent o) 拷贝构造函数3)、Intent(String action) 指定action类型的构造函数4)、Intent(String action, Uri uri) 指定Action类型和Uri的构造函数,URI主要是结合程序之间的数据共享ContentProvider5)、Intent(Context packageContext, Class<?> cls) 传入组件的构造函数,也就是上文提到的6)、Intent(String action, Uri uri, Context packageContext, Class<?> cls) 前两种结合体Intent有六种构造函数,3、4、5是最常用的,并不是其他没用!Intent(String action, Uri uri)  的action就是对应在AndroidMainfest.xml中的action节点的name属性值。在Intent类中定义了很多的Action和Category常量。 下面,我们来具体实现:1)、创建Intent 对象[java] view plain copyIntent intent = new Intent();  
2)、把我们的意图封装进Intent 对象中这里我们需要先了解 context :应用程序上下文,就是表示当前对象的一个语境,访问全局信息 的API这里使用了Intent 的 setclass 方法,我们来看看其定义:[java] view plain copy/** 
    * Convenience for calling {@link #setComponent(ComponentName)} with the 
    * name returned by a {@link Class} object. 
    * 
    * @param packageContext A Context of the application package implementing 
    * this class. 
    * @param cls The class name to set, equivalent to 
    *            <code>setClassName(context, cls.getName())</code>. 
    * 
    * @return Returns the same Intent object, for chaining multiple calls 
    * into a single statement. 
    * 
    * @see #setComponent 
    */  
   public Intent setClass(Context packageContext, Class<?> cls) {  
       mComponent = new ComponentName(packageContext, cls);  
       return this;  
   }  
这里 packageContext 即我们现在的 activity ,而Class<?> cls 则是我们的目的activity ,我们看看具体实现:[java] view plain copyintent.setClass(MainActivity.this,SecondActivity.class);  
 3)告诉系统执行操作[java] view plain copystartActivity(intent);  
实现这三步就能基本实现活动的跳转了; 三、向下一个活动传递数据       Intent 还可以在启动活动的时候传递数据的,我们来一起看一下。      在启动活动时传递数据的思路很简单,Intent 中提供了一系列putExtra()方法的重载,可以把我们想要传递的数据暂存在Intent 中,启动了另一个活动后,只需要把这些数据再从Intent 中取出就可以了。比如说FirstActivity 中有一个字符串,现在想把这个字符串传递到SecondActivity 中。注意这里putExtra()方法接收两个参数,第一个参数是键,用于后面从Intent中取值,第二个参数才是真正要传递的数据。1、putExtra 方法[java] view plain copypublic Intent putExtra(String name, String value) {  
    if (mExtras == null) {  
        mExtras = new Bundle();  
    }  
    mExtras.putString(name, value);  
        return this;  
}  
其中putstring 方法定义如下:[java] view plain copypublic void putString(String key, String value) {  
    unparcel();  
    mMap.put(key, value);  
}  
所以这里,我们可以这样实现[java] view plain copyputExtra("key","我是第一个活动");  
则会向跳转的活动发送字符串“我是第一个活动”; 2、接收方如何接受呢?      这里调用getStringExtra 函数传入相应的键值,就可以得到传递的数据了。这里由于我们传递的是字符串,所以使用getStringExtra()方法来获取传递的数据,如果传递的是整型数据,则使用getIntExtra()方法,传递的是布尔型数据,则使用getBooleanExtra()方法,以此类推[java] view plain copypublic String getStringExtra(String name) {  
    return mExtras == null ? null : mExtras.getString(name);  
}  
其会调用getString 函数:[java] view plain copypublic String getString(String key) {  
    unparcel();  
    Object o = mMap.get(key);  
    if (o == null) {  
        return null;  
    }  
    try {  
        return (String) o;  
    } catch (ClassCastException e) {  
        typeWarning(key, o, "String", e);  
        return null;  
    }  
}  
并将其显示在TextView 上:[java] view plain copy@android.view.RemotableViewMethod  
   public final void setText(CharSequence text) {  
       setText(text, mBufferType);  
   }  

 下面是实现具体代码:MainActivity 方[java] view plain copypackage cn.com.qiang.buttondemo;  
  
import android.os.Bundle;  
import android.app.Activity;  
import android.content.Intent;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
  
public class MainActivity extends Activity {  
  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
          
        Button button1 = (Button) findViewById(R.id.button1);  
          
        button1.setOnClickListener(new MyListon());  
    }  
      
    class MyListon implements OnClickListener{  
        @Override  
        public void onClick(View v) {  
            // TODO Auto-generated method stub  
        Intent intent = new Intent();  
        intent.setClass(MainActivity.this,SecondActivity.class);  
        intent.putExtra("key", "给你发个美女图片");  
        startActivity(intent);  
        }  
    }     
}  

SecondActivity 方[java] view plain copypackage cn.com.qiang.buttondemo;  
  
import android.app.Activity;  
import android.content.Intent;  
import android.os.Bundle;  
import android.widget.TextView;  
  
public class SecondActivity extends Activity {  
    @Override  
    protected void onCreate(Bundle savedInstanceState){  
        // TODO Auto-generated method stub  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_second);  
      
        Intent intent = getIntent();  
        String s = intent.getStringExtra("key");  
        TextView tv = (TextView) findViewById(R.id.tv);  
        tv.setText(s);  
    }  
}  

<activity   
            android:name=".SecondActivity">  
            
</activity> 

<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.helloworld.MainActivity" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world1" />
    
</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: