Activity带传参与返回码
为更好地从Activity跳转,并且带数据传递和关闭Activity,加上请求码与返回码得到数据。请看详细下面的例子。
让我们看一下原代码。虽然,只有代码,大家肯定看效果的。
package com.smart.activity; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; public class Main extends Activity { private static final String TAG = "Main"; // ANDROID系统,组件与组件之间是通过,INTENT进行通信的。 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Button button = (Button) this.findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Main.this, SmartActivity.class); // 打开应用的组件 intent.putExtra("id", 988); intent.putExtra("name", "老梁"); // Main.this.startActivity(intent); //这里请求码 Main.this.startActivityForResult(intent, 3); } }); } // 从第二个ACTIVITY返回的数据 @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "requestCode=" + requestCode + ",resultCode=" + resultCode); if (resultCode == 2) { data.getStringExtra("result"); Log.i(TAG, "result=" + data.getStringExtra("result")); } super.onActivityResult(requestCode, resultCode, data); } }
package com.smart.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class SmartActivity extends Activity { private TextView resultView; @Override protected void onCreate(Bundle savedInstanceState) { // 关于这行代码,是完成界面的代码 super.onCreate(savedInstanceState); setContentView(R.layout.smart); resultView = (TextView) this.findViewById(R.id.result); Intent intent = this.getIntent(); // 得到数据 int id = intent.getIntExtra("id", 0); String name = intent.getStringExtra("name"); resultView.setText("得到的参数为:--->id为:" + id + ", name为:" + name); Button button = (Button) this.findViewById(R.id.finish); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent1 = new Intent(); // 进行关闭 intent1.putExtra("result", "smart——android学习过程"); //这里返回码 SmartActivity.this.setResult(12,intent1); SmartActivity.this.finish(); } }); } }