您好,登錄后才能下訂單哦!
新建android工程:
之后再新建一個class:任意起名(我的是Acitvity2),但是要繼承activity;
同時在layout里面新建一個布局文件:
代碼實現如下:maniactivity
public class MainActivity extends Activity {
private Button btn_startActivity2;
private TextView tv_out;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_out=(TextView) findViewById(R.id.textView1);
btn_startActivity2=(Button) findViewById(R.id.btn_startActivity2);
btn_startActivity2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent(MainActivity.this,Activity2.class);
//intent.putExtra("hello", "hello world!!!");
Bundle data=new Bundle();
data.putString("hello", "hello yaowen613@github.com!!!");
//data.putString("hello", "15626102810");
//data.putString("hello", "794365939");
intent.putExtras(data);
//startActivity(intent);
startActivityForResult(intent, 0);
}
});
}
//接收并處理返回的data;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
String result = data.getStringExtra("result");
tv_out.setText(result);
super.onActivityResult(requestCode, resultCode, data);
}
}
新建類的代碼實現:
public class Activity2 extends Activity {
private TextView tv_out;
private Button btn_close;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
init();
}
private void init() {
// TODO Auto-generated method stub
tv_out=(TextView) findViewById(R.id.tv_out);
//tv_out.setText(getIntent().getStringExtra("hello"));
Bundle data=getIntent().getExtras();
String hello=data.getString("hello");
tv_out.setText(hello);
btn_close=(Button) findViewById(R.id.btn_close);
btn_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.putExtra("result", "hello MainActivity");
//startActivity(intent);
setResult(0, intent);
finish();
}
});
}
}
布局文件就不用我上代碼了,隨便你們自己任意設計;
另外,這樣直接運行,程序還是會拋異常強制退出,是因為新建的activity2這個class沒有在manifest里面注冊:注冊方法就是在application標簽里加入“<activity android:name=".Activity2"></activity>”這么一段話;如下圖::
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。