Android_2015-04-07 Android中Intent的使用

1. 什么是Intent

  1.1 Intent是Android程序中各个组件之间进行交互的一种方式,不仅可以指明当前组件想要执行的动作,还可以在不同组件之间传递数据.

    Intent一般可用于启动活动,启动服务,以及发送广播等场景.

2.Intent用法:两种用法 显式Intent和隐式Intent

  2.1 显式Intent, 我们用两个活动之间的切换来演示显示Intent

    2.1.1 Intent有多个函数的重载,其中有一个是 

      public Intent(Context packageContext, Class<?> cls) 

      第一个参数就是启动获取的上下文,第二个参数则是想要启动的目标活动

      首先创建两个布局页面,并且创建两个活动(Activity)

      MainActivity.cs 和 SecondActivity.cs

      创建了SecondActivity.cs活动之后,我们要在AndroidMainifest.xml中注册该活动,只需添加一行:<activity android:name=".SecondActivity"></activity>

      activity_main.xml(第一个布局文件)和second_layout.xml(第二个布局文件)

      activity_main.xml:

      

 1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     tools:context="${relativePackage}.${activityClass}" >
 6 
 7    <Button 
 8        android:id="@+id/btn01"
 9        android:layout_width="match_parent"
10        android:layout_height="wrap_content"
11        android:text="btn01"
12        />
13 
14 </RelativeLayout>

    second_layout.xml

    

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6     
 7     <Button 
 8         android:id="@+id/btn02"
 9         android:layout_width="match_parent"
10         android:layout_height="wrap_content"
11            android:text="Btn02"
12         />
13 
14 </LinearLayout>

    在MainActivity.cs中对按钮btn01添加如下方法:

    

1 Button button = (Button) findViewById(R.id.btn01); 
2         button.setOnClickListener(new Button.OnClickListener(){
3 
4             @Override
5             public void onClick(View v) {
6                 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
7                 startActivity(intent);
8             }
9         });

    则在点击btn01的时候会跳转到SecondActivity.cs

    为了显示second_layout.xml我们在SecondActivity.cs中指定布局页:setContentView(R.layout.second_layout);

      

    小弟新手,请多指教

  2.2 隐式Intent  下节继续

原文地址:https://www.cnblogs.com/liyajie/p/4398598.html