Android activity 參數(shù)傳遞 經(jīng)過(guò)網(wǎng)上的資料收集終于測(cè)試成功,可以兩個(gè)Activity 之間相互傳遞參數(shù)。先將部分代碼帖出來(lái)(關(guān)鍵代碼已注釋),僅供參考。
創(chuàng)新互聯(lián)公司主營(yíng)虞城網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,重慶APP開(kāi)發(fā)公司,虞城h5小程序開(kāi)發(fā)搭建,虞城網(wǎng)站營(yíng)銷(xiāo)推廣歡迎虞城等地區(qū)企業(yè)咨詢
第一個(gè)activity:activity_main
導(dǎo)入相關(guān)包
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
import android.app.Activity;
button 按鈕傳遞參數(shù):
private Button bt;
private TextView tw1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt=(Button)findViewById(R.id.btnBack);
tw1=(TextView)findViewById(R.id.edtRec);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it= new Intent();
//傳遞參數(shù)
it.putExtra("name", tw1.getText().toString());
it.setClass(MainActivity.this, ShowInfo.class);
// startActivity(it); //不接收返回值
startActivityForResult(it, 1); //接收返回值 這里參數(shù)必須>0 否則onActivityResult無(wú)法執(zhí)行
// MainActivity.this.finish(); //終止Activity
}
});
}
接收返回參數(shù):前面的按鈕必須設(shè)置為startActivityForResult(it, 1); //接收返回值
/**
* 接收帶有返回值的Activity方法
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
Log.i("Main", "requestCode:"+requestCode+"resultCode:"+resultCode);
//這里 requestCode=1,resultCode=-1
if(requestCode == 1){
tw1.setText(data.getStringExtra("return"));
}
// tw1.setText(data.getStringExtra("return"));
}
第二個(gè)activity ShowInfo:
private TextView tv1;
private Button btnBack;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_info);
//新頁(yè)面接收數(shù)據(jù)
Intent intent=this.getIntent();
String name=intent.getStringExtra("name");
Log.i("獲取到的name值為",name);
tv1 = (TextView)findViewById( R.id.edtRec );
tv1.setText("傳過(guò)來(lái)的值為:"+name);
btnBack=(Button)findViewById(R.id.btnBack);//定義返回按鈕
btnBack.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) //返回按鈕傳遞參數(shù)給主頁(yè)面
{
Intent intent=new Intent();
intent.putExtra("return", tv1.getText().toString()); //傳遞參數(shù)到return
setResult(RESULT_OK, intent);
finish(); //關(guān)閉當(dāng)前activity
}
});
}