关闭

Android中用Bundle在Activity间传递数据

标签: Activity间传递数据Bundle字符串转为大写字母Android用Bundle传递数据并返
1978人阅读 评论(0) 收藏 举报
分类:

转载请标明出处:http://blog.csdn.net/wu_wxc/article/details/49908017
本文出自【吴孝城的CSDN博客】

Android中往往会用Bundle来传递数据,并通过startActivity(Intent intent)或者startActivityForResult(Intent intent, int requestCode)方法来启动Activity,

startActivityForResult用来启动有返回的传递

下面是两个方法传递数据的小例子


startActivity(Intent intent)

要编辑的文件如下


activity_main.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">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
        <TextView
            android:text="帐户:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22sp"/>
        <EditText
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="8"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">
        <TextView
            android:text="密码:"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22sp"/>
        <EditText
            android:id="@+id/pas"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="8"
            android:password="true"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp">
        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="登录"
            android:textSize="20sp"/>
        <Button
            android:id="@+id/reset"
            android:layout_marginLeft="10dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="重置"
            android:textSize="20sp"/>
    </LinearLayout>

</LinearLayout>

bundle_activity.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">

   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
       <TextView
           android:text="用户名是:"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="20sp"/>
       <TextView
           android:id="@+id/show_name"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="20sp"/>
   </LinearLayout>
   <LinearLayout
       android:layout_width="wrap_content"
       android:layout_height="wrap_content">
       <TextView
           android:text="密码是:"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="20sp"/>
       <TextView
           android:id="@+id/shwo_pass"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="20sp"/>
   </LinearLayout>

    <TextView
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="返回"
        android:textSize="30sp"
        android:layout_marginTop="20dp" />

</LinearLayout>



MainActivity.java

package cn.wuxiaocheng.wu;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

    private EditText name, pas;
    private Button login, reset;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

    }

    private void initView() {
        name = (EditText) findViewById(R.id.name);
        pas = (EditText) findViewById(R.id.pas);
        login = (Button) findViewById(R.id.login);
        reset = (Button) findViewById(R.id.reset);

        login.setOnClickListener(loginView);
        reset.setOnClickListener(resetView);

    }

    private View.OnClickListener loginView = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String names = name.getText().toString();
            String pass = pas.getText().toString();
            Intent intent = new Intent(MainActivity.this, BundleActivity.class);
            //创建一个Bundle,用来在Activity间传递数据
            Bundle bundle = new Bundle();
            //用putString(String key, string value);来传递值,key为关键字,value为传递的值
            bundle.putString("name", names);
            bundle.putString("pas", pass);
            //将要传递的值附加到intent上
            intent.putExtras(bundle);
            //启动intent
            startActivity(intent);
        }
    };

    //当点击重置按钮时,将两个输入框清空
    private View.OnClickListener resetView = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            name.setText("");
            pas.setText("");
        }
    };
}

BundleActivity.java

package cn.wuxiaocheng.wu;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

/**
 * Created by Administrator on 2015/11/18.
 */
public class BundleActivity extends AppCompatActivity {

    private TextView showName, showPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bundle_activity);

        setTitle("你输入的用户名和密码");

        showName = (TextView) findViewById(R.id.show_name);
        showPass = (TextView) findViewById(R.id.shwo_pass);

        //定义一个Bundle,取出intent中附加的数据
        Bundle bundle = getIntent().getExtras();
        //通过name关键字取出用户名
        String showname = bundle.getString("name");
        //通过pas关键字取出密码
        String showpas = bundle.getString("pas");
        //给界面的两个TextView设置显示的内容
        showName.setText(showname);
        showPass.setText(showpas);

        //返回功能的实现
        TextView btn = (TextView) findViewById(R.id.back);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

新建Activity还要在AndroidManifest.xml添加配置

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.wuxiaocheng.wu" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".BundleActivity"/>
    </application>

</manifest>

其中第18行就是添加新建的Activity的代码

运行结果如下



源码下载



顺带写个将小写字母转为大写字母

startActivityForResult(Intent intent, int requestCode)

需要编辑的文件如下


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/et"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="转为大写"
        android:textSize="18sp"
        android:id="@+id/button"
        android:layout_below="@+id/tv"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="转换结果"
        android:id="@+id/tv"
        android:layout_below="@+id/et"
        android:layout_marginTop="10dp"
        android:textSize="20sp"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

activity_result.xml

<?xml version="1.0" encoding="utf-8"?>
<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="cn.wuxiaocheng.startactivityforresult.Result">

    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="转换"
        android:textSize="20sp"
        android:layout_marginTop="31dp" />

</RelativeLayout>


MainActivity.java

package cn.wuxiaocheng.startactivityforresult;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private EditText editText;
    private TextView textView;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        editText = (EditText) findViewById(R.id.et);
        textView = (TextView) findViewById(R.id.tv);
        button = (Button) findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("value", editText.getText().toString());
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, Result.class);
                intent.putExtras(bundle);
                //startActivityForResult(Intent intent, int requestCode);
                //第一个参数是调用的新的Activity,
                // 第二个参数是请求代码,就 >= 0。用来识别调用的Activity
                startActivityForResult(intent, 0);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            //请求代码为上面的0时
            case 0:
                Bundle bundle = data.getExtras();
                textView.setText(bundle.getString("result"));
        }
    }
}



Result.java

package cn.wuxiaocheng.startactivityforresult;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Result extends AppCompatActivity {

    private String value;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        value = bundle.getString("value");
        //assert,断言,判断value是否为空
        assert value != null;
        //.toUpperCase();方法用于把字符串转化为大字
        value = value.toUpperCase();

        Button button = (Button) findViewById(R.id.back);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("result", value);
                //.setResult()只返回结果,不带数据
                Result.this.setResult(RESULT_OK, intent);
                Result.this.finish();
            }
        });
    }
}

用到Activity要在清单文件里设置

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="cn.wuxiaocheng.startactivityforresult" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".Result" >
        </activity>
    </application>

</manifest>

第十八十九行就是

效果如下图




源码下载



1
1

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:216198次
    • 积分:3683
    • 等级:
    • 排名:第9135名
    • 原创:150篇
    • 转载:0篇
    • 译文:0篇
    • 评论:22条
    文章分类
    联系方式

    微信

    QQ

    我的微博