说明:初探Intent对象。这里主要讲使用Intent对象在Activity之间传递数据的方法。
例子:由MainActivity→OtherActivity的跳转过程中,把数据传递给OtherActivity并显示出来。
在讲步骤之前,先来看看Intent究竟是个什么东西先。
Intent对象的基本概念:
1、Intent对象是Android应用程序组件之一;
2、Intent对象在Android系统当中表示一种意图;
3、Intent当中最重要的内容是action和data。
步骤:1.在MainActivity里面生成一个Intent对象,在Intent对象里面使用putExtra()系列方法,把数据放到Intent对象当中去。
activity_main.xml里面放置一个Button,点击跳转到OtherActivity。
<Button
android:id="@+id/btnId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动第二个Activity" />然后生成Intent,使用putExtra()向Intent对象当中存储数据。
package com.away.b_04_intent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public 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.btnId);
button.setOnClickListener(new ButtonListener());
}
class ButtonListener implements OnClickListener{
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, OtherActivity.class);
intent.putExtra("com.away.b_04_intent.Age", 20);
intent.putExtra("com.away.b_04_intent.Name", "Away");
startActivity(intent);
}
}
}
2.在OtherActivity里面使用getXXXExtra()系列方法从Intent对象当中取出数据。package com.away.b_04_intent;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class OtherActivity extends Activity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.other);
Intent intent = getIntent();
int age = intent.getIntExtra("com.away.b_04_intent.Age", 10);
String name = intent.getStringExtra("com.away.b_04_intent.Name");
textView = (TextView) findViewById(R.id.textView);
textView.setText(name + ":" + age + "");
}
}效果图:
国庆过了。。。明天又要上班了。。。以后真想在家上班,不过在家整个人又会变得好懒的了。。。
原文地址:http://blog.csdn.net/ycwol/article/details/39859341