前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Activity数据传递

Activity数据传递

作者头像
分享达人秀
发布2018-02-05 15:24:18
1.1K0
发布2018-02-05 15:24:18
举报

在Android开发中,经常要在Activity之间传递数据。前面也学习了Activity和Intent相关基础,接下来一起来学习Activity的数据传递。

一、简介

通过前面的学习知道,Intent可以用来开启Activity,同样它也可以用来在Activity之间传递数据。Intent提供了多个重载的方法来携带额外的数据,如下所示。

  • putExtra(String name, xxx value):向 Intent 中按 key-value 对的形式存入数据。
  • getXxxExtra(String name):从Intent中按key取出指定类型的数据。
  • putExtras(Bundle data):向Intent中放入需要携带的数据包。
  • Bundle getExtras():取出Intent中所携带的数据包。

使用Intent传递数据只需调用putExtra()方法将想要存储的数据存在Intent中即可。当启动了另一个Activity后,再把这些数据从Intent中取出即可。其核心示例代码如下:

// 从MainActivity传递数据到
SecondActivityIntent intent = new Intent(MainActivity.this, SecondActivity.class);
String name = "admin ";
intent.putExtra( "extra_data_name",name);
startActivity(intent);

// 取出MainActivity传递过来的数据
Intent intent = getIntent();
String name = intent. getStringExtra( "extra_data_name");

还有另外一种方式,就是传递Bundle对象。Bundle对象包含了多个方法来存入数据和取出数据,如下所示。

  • putXxx(String key , Xxx data):向 Bundle 中放入 int、long 等各种类型的数据。
  • putSerializable(String key,Serializable data):向 Bundle 中放入一个可序列化的对象。
  • getXxx(String key):从Bundle中取出int、long等各种类型的数据。
  • getSerializable(String key, Serializable data):从 Bundle 中取出一个可序列化的对象。

使用Bundle对象传递数据的核心代码如下:

// 从MainActivity传递数据到
SecondActivityBundle bundle = new Bundle();
bundle.putString( "name", "Linda ");bundle.putInt( "age", 20 );
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtras(bundle);
startActivity(intent);

// 取出MainActivity传递过来的数据
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String stuName = bundle.getString( "name");
int stuAge = bundle.getString( "age");

在上述代码中,在接收Bundle对象封装的数据时,需要先创建对应的Bundle对象,然后再根据存入的key值取出value。其实用Intent传递数据以及对象时,它的内部也是调用了Bundle对象相应的put()方法,也就是说Intent内部也是用Bundle来实现数据传递的,只是封装了一层而已。

二、示例

接下来通过一个示例来学习两个Activity之间如何通过Bundle交换数据。

创建一个示例程序,非常简单,一共有两个界面,其中第一个界面有用户名、密码和性别等信息,然后有一个注册按钮,第二个界面包含多个文本框。让用户将信息填写完整后点击注册,将所有信息传入到第二个页面去模拟注册,这里就简单显示出来即可。

第一个Activity对应的布局文件(activity_main)的代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:layout_width="match_parent"    
android:layout_height="match_parent"    
android:orientation="vertical" >   
 <LinearLayout       
  android:id="@+id/regist_username_ll"        
  android:layout_width="match_parent"        
  android:layout_height="wrap_content"        
  android:layout_centerHorizontal="true"       
  android:layout_marginLeft="10dp"        
  android:layout_marginRight="10dp"        
  android:layout_marginTop="22dp"        
  android:orientation="horizontal" >      
<TextView            
android:layout_width="80dp"            
android:layout_height="wrap_content"            
android:gravity="right"            
android:paddingRight="5dp"            
android:text="用户名 :" />       
 <EditText           
  android:id="@+id/name_et"            
  android:layout_width="match_parent"            
  android:layout_height="wrap_content"            
  android:hint="请输入您的用户名"            
  android:textSize="14dp" />  
</LinearLayout>   
<LinearLayout       
 android:id="@+id/regist_password_ll"        
 android:layout_width="match_parent"        
 android:layout_height="wrap_content"        
 android:layout_below="@+id/regist_username_ll"        
 android:layout_centerHorizontal="true"        
 android:layout_marginLeft="10dp"        
 android:layout_marginRight="10dp"        
 android:layout_marginTop="5dp"        
 android:orientation="horizontal" >      
<TextView           
 android:layout_width="80dp"            
 android:layout_height="wrap_content"            
 android:gravity="right"            
 android:paddingRight="5dp"            
 android:text="密    码 :" />        
<EditText          
  android:id="@+id/password_et"            
  android:layout_width="match_parent"            
  android:layout_height="wrap_content"            
  android:hint="请输入您的密码"            
  android:inputType="textPassword"            
  android:textSize="14dp" />   
</LinearLayout>   
 <RadioGroup        
  android:id="@+id/sex_rg"        
  android:layout_width="wrap_content"        
  android:layout_height="wrap_content"        
  android:layout_below="@+id/regist_password_ll"        
  android:layout_marginLeft="30dp"        
  android:contentDescription="性别"        
  android:orientation="horizontal" >        
<RadioButton            
android:id="@+id/male_rb"            
android:layout_width="wrap_content"            
android:layout_height="wrap_content"            
android:checked="true"            
android:text="男" >        
</RadioButton>        
<RadioButton           
 android:id="@+id/female_rb"            
 android:layout_width="wrap_content"            
 android:layout_height="wrap_content"            
 android:text="女" />    
</RadioGroup>    
<Button        
android:id="@+id/register_btn"        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:layout_below="@+id/sex_rg"        
android:layout_centerHorizontal="true"        
android:layout_marginTop="24dp"        
android:text="注册" /></RelativeLayout>

在上述代码中,定义了一个相对布局RelativeLayout,该布局中创建了一个EditText和一个Button按钮,分别用于输入内容和单击“注册”按钮进行数据传递。

接下来创建一个用于数据接收的界面activity_second.xml,该界面的布局比较简单,只添加了三个TextView用来展示用户信息,因此不展示界面效果。activity_second.xml界面代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"   
 android:layout_width="match_parent"    
 android:layout_height="match_parent"    
 android:orientation="vertical">   
<TextView      
  android:id="@+id/name_tv"        
  android:layout_width="wrap_content"        
  android:layout_height="wrap_content"        
  android:gravity="center"        
  android:layout_marginTop="10dp"        
  android:textSize="20dp" />   
<TextView      
  android:id="@+id/password_tv"        
  android:layout_width="wrap_content"        
  android:layout_height="wrap_content"        
  android:gravity="center"        
  android:layout_marginTop="10dp"        
  android:textSize="20dp" />    
 <TextView        
 android:id="@+id/sex_tv"        
 android:layout_width="wrap_content"        
 android:layout_height="wrap_content"        
 android:gravity="center"        
 android:layout_marginTop="10dp"        
 android:textSize="20dp" /></LinearLayout>

当界面创建好之后,需要在MainActivity中编写与页面交互的代码,用于实现数据传递具体代码如下所示:

public class MainActivity extends AppCompatActivity { 
   private Button mRegisterBtn = null;    
   private EditText mNameEt = null;    
   private RadioButton mMaleRb = null;    
   private RadioButton mFemaleRb = null;    
   private EditText mPasswordEt = null;    
   protected void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_main);        
        mNameEt = (EditText) findViewById(R.id.name_et);        
        mPasswordEt = (EditText) findViewById(R.id.password_et);        
        mRegisterBtn = (Button) findViewById(R.id.register_btn);        
        mMaleRb = (RadioButton) findViewById(R.id.male_rb);        
        mFemaleRb = (RadioButton) findViewById(R.id.female_rb);        //点击发送按钮进行数据传递        
        mRegisterBtn.setOnClickListener(new View.OnClickListener() {           
         public void onClick(View v) {               
          register();            }        });    }    
          /**     * 注册     */   
           public void register() {        //创建Intent对象,启动SecondActivity       
            Intent intent = new Intent(this, SecondActivity.class);        //将数据存入Intent对象        
            intent.putExtra("name", mNameEt.getText().toString().trim());        
            intent.putExtra("password", mPasswordEt.getText().toString().trim());        
            String str = "";   
                 if(mMaleRb.isChecked()){          
                   str = "男";        }else if(mFemaleRb.isChecked()){           
                    str = "女";        }       
                     intent.putExtra("sex", str);    
                         startActivity(intent);    }}

在上述代码中,register()方法实现了获取用户输入数据,并且将Intent作为载体进行数据传递。接下来再创建一个SecondActivity,用于接收数据并展示,具体代码如下所示:

public class SecondActivity extends AppCompatActivity {   
 private TextView mNameTv = null;    
 private TextView mPasswordTv = null;    
 private TextView mSexTv = null;    
 protected void onCreate(Bundle savedInstanceState) {     
    super.onCreate(savedInstanceState);        
    setContentView(R.layout.activity_second);        
    Intent intent=getIntent();        
    String name = intent.getStringExtra("name");        
    String password = intent.getStringExtra("password");        
    String sex = intent.getStringExtra("sex");        
    mNameTv =(TextView) findViewById(R.id.name_tv);        
    mPasswordTv = (TextView) findViewById(R.id.password_tv);        
    mSexTv = (TextView) findViewById(R.id.sex_tv);        
    mNameTv.setText("用户名:" + name);        
    mPasswordTv.setText("密    码:" + password);        
    mSexTv.setText("性    别:" + sex);    
    }}

在上述代码中,通过getIntent()方法获取到Intent对象,然后通过该对象的getStringExtra()方法获取输人的用户名,并将得到的用户名绑定在TextView控件中进行显示。需要注意的是,getStringExtra(String str)方法传人的参数必须是MainActivity中intent.putExtra()方法中传人的key,否则会返回null。

接下来在清单文件中,配置Activity,具体代码如下所示:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"          
package="com.jinyu.cqkxzsxy.android.activity.userregister">    
<application        
android:allowBackup="true"        
android:icon="@mipmap/ic_launcher"        
android:label="@string/app_name"        
android:roundIcon="@mipmap/ic_launcher_round"        
android:supportsRtl="true"        
android:theme="@style/AppTheme">        
<activity android:name=".MainActivity"                  
android:label="填写用户信息">            <intent-filter>                
<action android:name="android.intent.action.MAIN" />                

<category android:name="android.intent.category.LAUNCHER" />           
 </intent-filter>        </activity>        
 <activity android:name=".SecondActivity"                
   android:label="用户注册信息"></activity>    
   </application></manifest>

需要注意的是,android:label属性是用来指定显示在标题栏上的名称的,如桌Activity设置了该属性,则跳到该Activity页面时标题栏会显示在Activity中配置的名称,否则显示在Application中配置的名称。

运行程序,在MainActivity的文本框中输入对应信息,可以看到左图所示效果。单击“注册”按钮,此时会跳转到SecondActivity界面,显示输人的信息,如右图所示。

从上图中可以看出,MainActivity中输入的数据username成功地传递给SecondActivity,这就是使用Intent进行不同界面传递数据的用法。

本节学习了将简单的数据从MainActivity传递到SecondActivity,下期学习数据如何从SecondActivity回传到MainActivity。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2017-10-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 分享达人秀 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档