关于android中Bundle的使用

 

1、Android using Bundle for sharing variables

注:android中使用Bundle来共享变量,下例中Activity1和Activity2通过bundle共享一个变量myValue  

Sharing variables between Activities is quite important point during development time of your Application. This  Example suppose Activity1 from where you run up other Activity2 based on your selection from submenu.   You gonna share variable myValue

From Activity1

Intent intent = new Intent(this,myActivity2.class);
Bundle bundle = new Bundle();
bundle.putString(“myValue“, myValue);
intent.putExtras(bundle);
navigation.this.startActivity(intent);

In Activity2

Bundle bundle = getIntent().getExtras();
act2MyValue= bundle.getString(“myValue“);

Now is your application powered to share variables between two different activities.

2、

Bundle is generally used for passing data between various Activities of android. It depends on you what type of values you want to pass but bundle can hold all types of values and pass to the new activity.

You can use it like .....

Intent intent = new
Intent(getApplicationContext(),SecondActivity.class);
intent.putExtra("myKey",AnyValue);
startActivity(intent);

Now you can get the passed values by...

Bundle extras = intent.getExtras();
String tmp = extras.getString("myKey");

3、

In this example, the main Activity (appropriately named ‘MainActvity‘) will pass information to a sub-activity (called SecondaryActivity).  SecondaryActivity will allow you to alter that information and then return it to MainActivity. The bundle of information will be sent back and forth between the Activity objects via an Intent object.

In order to pass the information we‘ll create our Intent object and do two things with it before sending it off.  First, we‘ll specify SecondaryActivity as the target by passing it into the Intent‘s constructor.  Then we‘ll stuff the information into it (the information is stored in a ‘Bundle‘ object that lives inside the Intent - the Bundle is created when you call the putExtras() method of the Intent object).  Once our Intent is ready to go, our MainActivity will simply launch it by passing it as a parameter into startActivityForResult().

When SecondaryActivity is created, it will check to see if an Intent is available. If so, it wil extract the data from the Bundle and put it into an EditText so that you can alter it.  Then you can click a button to send it back to MainActivity.  When the button is clicked, a new Intent is created with the updated information stuffed into a Bundle.  SecondaryActivity then calls setResult() which will return the information back to MainActivity.

It‘s important to note that when you pass information around like this, you‘ll have to add an entry into the AndroidManifest.xml file.  I always seem to forget this step.  You‘ll have to add the following line of code into the <application> section:

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

Here‘s the code...

This is the layout file for MainActivity (main.xml)...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="MAIN ACTIVITY"/>
    <EditText android:id="@+id/editText1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
    <Button android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click To Launch Secondary Activity"/>
</LinearLayout>

Here‘s the code for the MainActivity class...

package com.remwebdevelopment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener {
    private final int SECONDARY_ACTIVITY_REQUEST_CODE=0;
    private EditText mEditText1;
    private Button mButton1;
    //DONT FORGET: to add SecondaryActivity to the manifest file!!!!!
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mEditText1 = (EditText)findViewById(R.id.editText1);
        mButton1 = (Button)findViewById(R.id.button1);
        mButton1.setOnClickListener(this);
    }
    public void onClick(View view){
        if(view == mButton1){
            //create a new intent and specify that it‘s target is SecondaryActivity...
            Intent intent = new Intent(getApplicationContext(),SecondaryActivity.class);
            //load the intent with a key "myKey" and assign it‘s value
            //to be whatever has been entered into the text field...
            intent.putExtra("myKey",mEditText1.getText().toString());
            //launch the secondary activity and send the intent along with it
            //note that a request code is passed in as well so that when the
            //secondary activity returns control to this activity,
            //we can identify the source of the request...
            startActivityForResult(intent, SECONDARY_ACTIVITY_REQUEST_CODE);
        }
    }
    //we need a handler for when the secondary activity finishes it‘s work
    //and returns control to this activity...
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent){
        super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();
        mEditText1.setText(extras != null ? extras.getString("returnKey"):"nothing returned");
    }
}

Here‘s the layout file for SecondaryActivity (secondary_activity.xml)...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:text="SECONDARY ACTIVITY"/>
    <EditText android:id="@+id/txtSecondary"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"/>
    <Button android:id="@+id/btnSecondary"
            android:text="Click To Return to Main Activity"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"/>
</LinearLayout>

Finally, here‘s the code for the SecondaryActivity class...

package com.remwebdevelopment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class SecondaryActivity extends Activity{
    private EditText mEditText2;
    private Button mButton2;
    private String mIntentString;

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        setContentView(R.layout.secondary_activity);

        mEditText2 = (EditText)findViewById(R.id.txtSecondary);
        mButton2 = (Button)findViewById(R.id.btnSecondary);
        //add the event handler for the button...
        mButton2.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                mIntentString = mEditText2.getText().toString();
                //create a new intent...
                Intent intent = new Intent();
                //add "returnKey" as a key and assign it the value
                //in the textbox...
                intent.putExtra("returnKey",mEditText2.getText().toString());
                //get ready to send the result back to the caller (MainActivity)
                //and put our intent into it (RESULT_OK will tell the caller that
                //we have successfully accomplished our task..
                setResult(RESULT_OK,intent);
                //close this Activity...
                finish();
            }
        });

        //if the activity is being resumed...
        mIntentString = savedInstanceState != null ? savedInstanceState.getString("myKey"):null;

        //check to see if a Bundle is .
        if(mIntentString == null){
            //get the Bundle out of the Intent...
            Bundle extras = getIntent().getExtras();
            //check to see if "myKey" is in the bundle, if so then assign it‘s value
            // to mIntentString  if not, assign "nothing passed in" to mIntentString...
            mIntentString = extras != null ? extras.getString("myKey") : "nothing passed in";
        }
        //set the textbox to display mIntentString...
        mEditText2.setText(mIntentString);
    }

}
时间: 2024-10-22 15:09:35

关于android中Bundle的使用的相关文章

Android中的Parcel机制 实现Bundle传递对象

Android中的Parcel机制    实现了Bundle传递对象    使用Bundle传递对象,首先要将其序列化,但是,在Android中要使用这种传递对象的方式需要用到Android Parcel机制,即,Android实现的轻量级的高效的对象序列化和反序列化机制. JAVA中的Serialize机制,译成串行化.序列化……,其作用是能将数据对象存入字节流当中,在需要时重新生成对象.主要应用是利用外部存储设备保存对象状态,以及通过网络传输对象等.        Android中的新的序列

【转】Android中intent传递对象和Bundle的用法

原文网址:http://blog.csdn.net/lixiang0522/article/details/8642202 android中的组件间传递的对象一般实现Parcelable接口,当然也可以使用java的Serializable接口,前者是android专门设计的,效率更高,下面我们就来实现一个Parcelabel. 1. 创建一个类实现Parcelable接口,具体实现如下: [java] view plain copy package com.hebaijun.testparce

Android中的IPC方式(一)—— Bundle、文件共享、Messenger

1. 使用Bundle Android中的Activity.Service和Receiver都是支持在 Intent 中传递 Bundle 数据的,Bundle实现了 Parcelable 接口,它可以方便的在不同进程间传输.当我们在一个进程中启动了另一个进程的 Activity.Service 和 Receiver,就可以在 Bundle 中附加需要传输给远程进程的信息并通过 Intent 发送.注意:传输的数据必须能够被序列化,比如基本数据类型.实现Serializable 或 Parcel

谈谈-Android中的接口回调技术

Android中的接口回调技术有很多应用的场景,最常见的:Activity(人机交互的端口)的UI界面中定义了Button,点击该Button时,执行某个逻辑. 下面参见上述执行的模型,讲述James对Android接口回调技术的理解(结合前人的知识和自己的实践). 使用一个比喻很形象地说明:客户端有个疑问打电话请教服务端,但服务端无法现场给出解答,相互之间约定:服务端一旦有答案,使用电话的方式反馈给客户端. 以上有三个主体:客户端.服务端和接口(方式). 接口回调的原理框图说明: Demo界面

浅谈android中仅仅使用一个TextView实现高仿京东,淘宝各种倒计时

今天给大家带来的是仅仅使用一个TextView实现一个高仿京东.淘宝.唯品会等各种电商APP的活动倒计时.最近公司一直加班也没来得及时间去整理,今天难得休息想把这个分享给大家,只求共同学习,以及自己后续的复习.为什么会想到使用一个TextView来实现呢?因为最近公司在做一些优化的工作,其中就有一个倒计时样式,原来开发的这个控件的同事使用了多个TextView拼接在一起的,实现的代码冗余比较大,故此项目经理就说:小宏这个就交给你来优化了,并且还要保证有一定的扩展性,当时就懵逼了.不知道从何处开始

Android初级教程:Android中解析方式之pull解析

在安卓中有很多种解析方式.按照大方向有xml解析和json解析.而,细致的分,xml和json解析各有自己的很多解析方式.今天这一篇主要介绍xml解析中的pull解析.对于xml的解析方式,我之前在javaweb一些知识中有写过dom和dom4j等等解析方式.有兴趣的读者可以去javaweb篇里面找相关的内容. 先自定义一个数据源,假设就是访问服务器返回的xml数据文件名称为weather.xml: <?xml version='1.0' encoding='utf-8' standalone=

Android基础入门教程——8.1.3 Android中的13种Drawable小结 Part 3

Android基础入门教程--8.1.3 Android中的13种Drawable小结 Part 3 标签(空格分隔): Android基础入门教程 本节引言: 本节我们来把剩下的四种Drawable也学完,他们分别是: LayerDrawable,TransitionDrawable,LevelListDrawable和StateListDrawable, 依旧贴下13种Drawable的导图: 1.LayerDrawable 层图形对象,包含一个Drawable数组,然后按照数组对应的顺序来

Android基础入门教程——8.1.2 Android中的13种Drawable小结 Part 2

Android基础入门教程--8.1.2 Android中的13种Drawable小结 Part 2 标签(空格分隔): Android基础入门教程 本节引言: 本节我们继续来学习Android中的Drawable资源,上一节我们学习了: ColorDrawable:NinePatchDrawable: ShapeDrawable:GradientDrawable!这四个Drawable~ 而本节我们继续来学习接下来的五个Drawable,他们分别是: BitmapDrawable:Insert

android中的用户资源访问(一)

这几天要总结一下android开发中的用户资源访问. android中的用户资源存在项目工程中res文件夹下,有字符串.颜色.大小.数组.布局.样式.主题等资源,这些资源可以在xml文件中引用,也可以在android源码文件中使用,今天总结一下字符串.颜色.大小.数组.布局和图片资源. 总的来说,在xml文件中引用的格式为[<package>.]@/XXX/name:在源码中引用格式是[<package>.]R.XXX.name. 先贴上在xml文件中引用的代码(在布局xml文件中