android onActivityResult回调方法示例

package com.example.activityforresult;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity
{
    public static int RESULT_OK = 5;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button mFirstButton = (Button) findViewById(R.id.first);
		Button secondButton = (Button) findViewById(R.id.second);
		mFirstButton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				GoToFirstActivity();
			}
		});
		secondButton.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				GoToSencondActivity();
			}
		});

	}

	private void GoToFirstActivity()
	{
		startActivityForResult(new Intent(MainActivity.this, FirstActivity.class), 1);
	}

	private void GoToSencondActivity()
	{
		startActivityForResult(new Intent(MainActivity.this, SecondActivity.class), 2);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	/**
	 * 
	 * 函数名称 :onActivityResult 功能描述 : 回调函数 参数说明 :
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 *            返回值:
	 * 
	 *            修改记录: 日期 :2013-3-25 下午2:24:25 修改人: 描述 :
	 * 
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		switch (requestCode)
		{
			case 1:
				// TODO
				if (resultCode == RESULT_OK)
				{
					String getData = data.getStringExtra("first");
					Log.d("TAG", getData);
				}
				break;
			case 2:
				// TODO
				if (resultCode == RESULT_OK)
				{
					String getData = data.getStringExtra("second");
					Log.d("TAG", getData);
				}
				break;
			default:
				break;
		}
	}
}

  

package com.example.activityforresult;

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

public class FirstActivity extends Activity
{
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.first_activity);
		Button button = (Button) findViewById(R.id.resultbutton1);
		button.setOnClickListener(new View.OnClickListener()
		{
			
			@Override
			public void onClick(View v)
			{
				Intent intent = new Intent();
				intent.putExtra("first", "first");
				setResult(MainActivity.RESULT_OK, intent);
				finish();
			}
		});
	}
}

  

posted @ 2013-03-25 14:53  呆呆笨笨  阅读(581)  评论(0编辑  收藏  举报