Android bundle傳遞數據簡例

package com.yanjun;


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;
import android.widget.EditText;

public class MainActivity extends Activity {
        /** Called when the activity is first created. */
  EditText editText1;
  EditText editText2;
  Button button ;
        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.main);
                button = (Button) findViewById(R.id.button1);
                button.setOnClickListener(new OnClickListener() {
        
      public void onClick(View v) {
        // TODO Auto-generated method stub
        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
        String nameString = editText1.getText().toString();
        String ageString = editText2.getText().toString();
        Intent intent = new Intent();
        intent.setClass(MainActivity.this, SubActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("name", nameString);
        bundle.putString("age", ageString);
        intent.putExtras(bundle);
        startActivity(intent);
        
      }
    });
        }
}
package com.yanjun;

import android.app.Activity;

import android.os.Bundle;
import android.widget.TextView;

public class SubActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
    TextView textView = (TextView) findViewById(R.id.textView1);
    TextView textView2 = (TextView) findViewById(R.id.textView2);
    Bundle bundle = this.getIntent().getExtras();
    String nameString = bundle.getString("name");
    String ageString = bundle.getString("age");
    textView.setText("輸入姓名爲--->" + nameString);
    textView2.setText("輸入年齡爲--->" + ageString);
  }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章