• Android 数据传递(一) Activity之间的数据传递


    bundle

    Google Bundle类说明

    Bundle类是一个key-value对。Activity之间的数据通信可以通过bundle类来实现数据的存储。即将数据放入bundle里面,将Bundle传递。他的用法如下:

    //新建Bundle,将数据放入bundle类里面
    Bundle mBundle = new Bundle();
    mBundle.putString("flag" , "1");
    //新建一个intent对象,并将该bundle加入这个intent对象。
    Intent intent = new Intent();              intent.setClass(FirstActivity.this, SecondActivity.class);
           intent.putExtras(mBundle);
           startActivity(intent);
    

    startActivityForResult

    这里仅仅是将数据传到第二个Activity,不需要返回的结果。这个例子只是说明Bundle的应用。下面主要讲解两个Activity之间互相的数据传递,即用startActivityForResult (Intent intent, int requestCode)
    这是requestCode是请求码,当我们需要为startActivityForResult()方法传入一个请求码(第二个参数)。请求码的值是根据业务需要由自已设定,用于标识请求来源。例如:一个Activity有两个按钮,点击这两个按钮都会打开同一个Activity,不管是那个按钮打开新Activity,当这个新Activity关闭后,系统都会调用前面ActivityonActivityResult(int requestCode, int resultCode, Intent data)方法。在onActivityResult()方法如果需要知道新Activity是由那个按钮打开的,并且要做出相应的业务处理,这时可以这样做:

    @Override  public void onCreate(Bundle savedInstanceState) {
            ....
            button1.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v) {
                    startActivityForResult (new Intent(MainActivity.this, NewActivity.class), 1);
    
               }
    
            });
            button2.setOnClickListener(new View.OnClickListener(){
                public void onClick(View v) {
                     startActivityForResult (new Intent(MainActivity.this, NewActivity.class), 2);
    
                }
    
            });
    
                              
           @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                   switch(requestCode){
                       case 1:
                       //来自按钮1的请求,作相应业务处理
                       case 2:
                       //来自按钮2的请求,作相应业务处理
                    }
              }
    }
                 
    

    在跳入的新的Activity中,使用setResult(int resultCode , Intent data) 实现这个Activitie关闭时向之前的Activity返回数据。这里有一个参数是resultCode 结果码。
    在一个Activity中,可能会使用startActivityForResult()方法打开多个不同的Activity处理不同的业务,当这些新Activity关闭后,系统都会调用前面ActivityonActivityResult(int requestCode, int resultCode, Intent data)方法。为了知道返回的数据来自于哪个新Activity,在onActivityResult()方法中可以这样做(ResultActivityNewActivity为要打开的新Activity):

    public class ResultActivity extends Activity {
           .....
           ResultActivity.this.setResult(1, intent);
           ResultActivity.this.finish();
    }
    public class NewActivity extends Activity {
           ......
            NewActivity.this.setResult(2, intent);
            NewActivity.this.finish();
    }
    public class MainActivity extends Activity { // 在该Activity会打开ResultActivity和NewActivity
           @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                   switch(resultCode){
                       case 1:
                       // ResultActivity的返回数据
                       case 2:
                        // NewActivity的返回数据
                    }
              }
    } 
    

    下面是个具体的例子。我们新建3个Activity然后从第一个Activity中分别有两个选项跳入不同的Activity,然后不同的Activity返回不同的结果显示在第一个Activity。
    下面分别是三个activity的布局文件

    #activity_first.xml
    <?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">
    
        <TextView
            android:id="@+id/first"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_above="@+id/second"
            android:layout_marginBottom="20dp"
            android:textColor="@android:color/holo_red_light"
            android:text="传入到第二个activity"/>
    
        <TextView
            android:id="@+id/second"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginBottom="20dp"
            android:textColor="@android:color/holo_red_light"
            android:text="传入到第三个activity"/>
    
        <TextView
            android:id="@+id/secondresult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/holo_blue_bright"
            android:layout_below="@+id/second"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="20dp"
            android:textSize="25sp"
            android:text="第二个Activity初始文本"/>
    
        <TextView
            android:id="@+id/thirdresult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/holo_green_light"
            android:layout_below="@+id/secondresult"
            android:layout_centerHorizontal="true"
            android:layout_margin="10dp"
            android:textSize="25sp"
            android:text="第三个Activity初始文本"/>
    
    </RelativeLayout>
    
    
    #activity_second.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">
    
        <TextView
            android:id="@+id/ok"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:textColor="@android:color/holo_red_light"/>
    </RelativeLayout>
    
    #activity_third.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">
    
        <TextView
            android:id="@+id/error"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_below="@+id/ok"
            android:textColor="@android:color/holo_red_light"/>
    </RelativeLayout>
    

    下面分别是三个Activity

    #FirstActivity
    
    public class FirstActivity extends AppCompatActivity implements View.OnClickListener{
    
        private TextView first;
        private TextView second;
    
        private TextView secondresult;
        private TextView thirdresult;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_first);
            first = (TextView)findViewById(R.id.first);
            second = (TextView) findViewById(R.id.second);
            first.setOnClickListener(this);
            second.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.first:
                    Bundle fbundle = new Bundle();
                    fbundle.putString("Second" , "Ok");
                    Intent fintent = new Intent(FirstActivity.this, SecondActivity.class);
                    fintent.putExtras(fbundle);
                    startActivityForResult(fintent, 1);
                    break;
                case R.id.second:
                    Bundle sbundle = new Bundle();
                    sbundle.putString("Third" , "Error");
                    Intent sintent = new Intent(FirstActivity.this, ThirdActivity.class);
                    sintent.putExtras(sbundle);
                    startActivityForResult(sintent, 2);
                    break;
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (resultCode){
                case 2:
                    secondresult = (TextView) findViewById(R.id.secondresult);
                    secondresult.setText(data.getExtras().getString("second"));
                    break;
                case 3:
                    thirdresult = (TextView) findViewById(R.id.thirdresult);
                    thirdresult.setText(data.getExtras().getString("third"));
                    break;
            }
    
        }
    }
    
    #SecondActivity
    public class SecondActivity extends AppCompatActivity implements View.OnClickListener{
    
        private TextView ok;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
            ok = (TextView) findViewById(R.id.ok);
            ok.setText(getIntent().getExtras().getString("Second"));
            ok.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ok :
                    Bundle bundle = new Bundle();
                    bundle.putString("second","我的第二个Activity的数据");
                    Intent intent = new Intent(SecondActivity.this, FirstActivity.class);
                    intent.putExtras(bundle);
                    setResult(2, intent);
                    finish();
                    break;
            }
        }
    }
    
    #ThirdActivity
    public class ThirdActivity extends AppCompatActivity implements View.OnClickListener{
    
        private TextView error;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_third);
            error = (TextView)findViewById(R.id.error);
            error.setText(getIntent().getExtras().getString("Third"));
            error.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.error:
                    Bundle bundle = new Bundle();
                    bundle.putString("third", "我的第三个Activity的数据");
                    Intent intent = new Intent(ThirdActivity.this, FirstActivity.class);
                    intent.putExtras(bundle);
                    setResult(3, intent);
                    finish();
                    break;
            }
        }
    }
    

    效果图如下:

    现在我们更改一下界面,改为在FirstActivity中有两个选项同时传入一个Activity中,对其进行不同的修改。
    这里我们修改下第一个Activity的view

    #firstView
    <?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">
    
        <TextView
            android:id="@+id/first"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_above="@+id/second"
            android:layout_marginBottom="20dp"
            android:textColor="@android:color/holo_red_light"
            android:text="传入OK"/>
    
        <TextView
            android:id="@+id/second"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:layout_marginBottom="20dp"
            android:textColor="@android:color/holo_red_light"
            android:text="传入Error"/>
    
        <TextView
            android:id="@+id/result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/holo_blue_bright"
            android:layout_below="@+id/second"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="20dp"
            android:textSize="25sp"
            android:text="显示"/>
    
        <TextView
            android:id="@+id/thirdresult"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="@android:color/holo_green_light"
            android:layout_below="@+id/secondresult"
            android:layout_centerHorizontal="true"
            android:layout_margin="10dp"
            android:textSize="25sp"
            android:text=""/>
    
    </RelativeLayout>
    

    以及第二个activity的view

    #second
    <?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">
    
        <TextView
            android:id="@+id/show"
            android:layout_centerInParent="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="25sp"
            android:textColor="@android:color/holo_red_light"/>
    </RelativeLayout>
    

    以及第一个Activity和第二个Activity 根据第一个Activity的选项,使第二个Activity显示不同的结果,当第二个Activity结束的时候,根据requestCode不同,在第一个Activity显示不同的结果

    #firstActivty
    public class FirstActivity extends AppCompatActivity implements View.OnClickListener{
    
        private TextView first;
        private TextView second;
        private TextView result;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_first);
            first = (TextView)findViewById(R.id.first);
            second = (TextView) findViewById(R.id.second);
            first.setOnClickListener(this);
            second.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.first:
                    Bundle fbundle = new Bundle();
                    fbundle.putString("Second" , "Ok");
                    Intent fintent = new Intent(FirstActivity.this, SecondActivity.class);
                    fintent.putExtras(fbundle);
                    startActivityForResult(fintent, 1);
                    break;
                case R.id.second:
                    Bundle sbundle = new Bundle();
                    sbundle.putString("Second" , "Error");
                    Intent sintent = new Intent(FirstActivity.this, SecondActivity.class);
                    sintent.putExtras(sbundle);
                    startActivityForResult(sintent, 2);
                    break;
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode){
                case 1:
                    result = (TextView) findViewById(R.id.result);
                    result.setText("OK");
                    break;
    
                case 2:
                    result = (TextView) findViewById(R.id.result);
                    result.setText("Error");
                    break;
            }
    
        }
    }
    
    #SecondActivity
    public class SecondActivity extends AppCompatActivity implements View.OnClickListener{
    
        private TextView show;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
            show = (TextView) findViewById(R.id.show);
            show.setText(getIntent().getExtras().getString("Second"));
            show.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.show :
                    finish();
                    break;
            }
        }
    }
    

    结果如下:


  • 相关阅读:
    Java异常处理和设计
    一次qps测试实践
    Alternate Task UVA
    Just Another Problem UVA
    Lattice Point or Not UVA
    Play with Floor and Ceil UVA
    Exploring Pyramids UVALive
    Cheerleaders UVA
    Triangle Counting UVA
    Square Numbers UVA
  • 原文地址:https://www.cnblogs.com/qifengshi/p/5267302.html
Copyright © 2020-2023  润新知