关闭

StartActivityForResult简单使用

85人阅读 评论(0) 收藏 举报

=============>MainActivity

package com.text.startactivityforresult;


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 MainActivity extends Activity {
private Button btn;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button) findViewById(R.id.button1);
tv=(TextView) findViewById(R.id.textView1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, 1);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1&&resultCode==2){
String str=data.getStringExtra("data");
tv.setText(str);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}


===========>

SecondActivity

package com.text.startactivityforresult;


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


public class SecondActivity extends Activity{
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
btn=(Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent data=new Intent();
data.putExtra("data","Beijing");
setResult(2, data);
finish();
}
});
}
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:436次
    • 积分:63
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档