首页 > 代码库 > activity通过onActivityResult间数据交互
activity通过onActivityResult间数据交互
首先要创建2个activity 分别为MainActivity和OneActiivity
MainActivity代码如下:
package com.tp.soft.app;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener{ private Button mTzBtn; private TextView mShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTzBtn = (Button) findViewById(R.id.tzBtn); mTzBtn.setOnClickListener(this); mShow = (TextView) findViewById(R.id.showMsg); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == 1){ String msg = data.getStringExtra("FromOneActivity"); mShow.setText(msg); } } @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, OneActivity.class); String content = "Hello,OneActivity"; intent.putExtra("FromMainActivity", content); startActivityForResult(intent, 1); }}
其中调用
startActivityForResult(intent, 1);中的1就是
onActivityResult返回的requestCode。
OneActivity代码如下:
package com.tp.soft.app;import android.os.Bundle;import android.app.Activity;import android.content.Intent;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class OneActivity extends Activity implements OnClickListener { private Button mbackBtn; private TextView mShow; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_one); mbackBtn = (Button) findViewById(R.id.backBtn); mbackBtn.setOnClickListener(this); mShow = (TextView) findViewById(R.id.showTxt); Intent intent = getIntent(); String show = intent.getStringExtra("FromMainActivity"); mShow.setText(show); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.one, menu); return true; } @Override public void onClick(View v) { Intent intent = new Intent(OneActivity.this, MainActivity.class); intent.putExtra("FromOneActivity", "Hello,MainActivity"); setResult(RESULT_OK, intent); finish(); }}
activity通过onActivityResult间数据交互
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。