StartActivityForResult简单使用

=============>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();
}
});
}
}

阅读更多
上一篇单例模式
下一篇StartService启动服务的生命周期
博主设置当前文章不允许评论。

startActivityForResult简单使用

2013年11月22日 438KB 下载

没有更多推荐了,返回首页

关闭
关闭