码迷,mamicode.com
首页 > 其他好文 > 详细

关于intent传递数据的练习

时间:2015-05-17 18:31:33      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:

1、主Activity里有两个Button,点击每个Button都调用第二个NewActivity。

2、从NewActivity里返回后,判断是从两个Button中的哪一个启动的NewActivity,并显示在TextView或者Toast上。

 

MainActivity

package com.example.intenttest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity
{

    private Button btn1, btn2;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);

        btn1 = (Button) findViewById(R.id.bnt1);
        btn2 = (Button) findViewById(R.id.bnt2);

        btn1.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                startActivityForResult(new Intent(MainActivity.this, NewActivity.class), 1);
            }
        });

        btn2.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View arg0)
            {
                // TODO Auto-generated method stub
                startActivityForResult(new Intent(MainActivity.this, NewActivity.class), 2);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // TODO Auto-generated method stub
        switch (requestCode)
        {
            case 1 :
                Toast.makeText(MainActivity.this, "第一个Button", Toast.LENGTH_SHORT).show();
                break;
            case 2 :
                Toast.makeText(MainActivity.this, "第二个Button", Toast.LENGTH_SHORT).show();
                break;
            default :
                break;
        }
    }

}

 

NewActivity

package com.example.intenttest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;

public class NewActivity extends Activity
{

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.new_activity);
        setResult(RESULT_OK, new Intent().putExtra("result", "返回的数据"));
    }

}

关于intent传递数据的练习

标签:

原文地址:http://www.cnblogs.com/qq28902581/p/4510102.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!