MainActivity:
1 package com.example.plus; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 import android.widget.EditText; 9 import android.widget.TextView; 10 11 public class MainActivity extends Activity { 12 13 private Button Count; 14 private EditText Plus1; 15 private EditText Plus2; 16 17 protected void onCreate(Bundle savedInstanceState) { 18 super.onCreate(savedInstanceState); 19 setContentView(R.layout.activity_main); 20 21 Plus1 = (EditText) findViewById(R.id.plusone); 22 Plus2 = (EditText) findViewById(R.id.plustwo); 23 24 Count = (Button) findViewById(R.id.count); 25 Count.setText("Count"); 26 27 TextView SymbolPlus = (TextView) findViewById(R.id.symbol); 28 SymbolPlus.setText(R.string.symbol); 29 30 Count.setOnClickListener(new View.OnClickListener() { 31 32 @Override 33 public void onClick(View arg0) { 34 String Plus1str = Plus1.getText().toString(); 35 String Plus2str = Plus2.getText().toString(); 36 37 // 把控件的值放到Intent的Extra里面 38 Intent ToResult = new Intent(); 39 ToResult.putExtra("one", Plus1str); 40 ToResult.putExtra("two", Plus2str); 41 42 ToResult.setClass(MainActivity.this, Result.class); 43 MainActivity.this.startActivity(ToResult); 44 45 } 46 }); 47 } 48 }
Resule:
1 package com.example.plus; 2 3 import android.os.Bundle; 4 import android.widget.TextView; 5 import android.app.Activity; 6 import android.content.Intent; 7 8 public class Result extends Activity { 9 private TextView answer; 10 11 protected void onCreate(Bundle savedInstanceState) { 12 super.onCreate(savedInstanceState); 13 setContentView(R.layout.result); 14 15 answer = (TextView) findViewById(R.id.Answer); 16 17 Intent intent = getIntent(); 18 19 String Plus1 = intent.getStringExtra("one"); 20 String Plus2 = intent.getStringExtra("two"); 21 22 int num1 = Integer.parseInt(Plus1); 23 int num2 = Integer.parseInt(Plus2); 24 25 int result = num1 + num2; 26 27 answer.setText(result + ""); 28 } 29 }
Main.xml
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:tools="http://schemas.android.com/tools" 4 android:layout_width="fill_parent" 5 android:layout_height="fill_parent" 6 android:orientation="vertical" 7 tools:context=".MainActivity" > 8 9 <EditText 10 android:id="@+id/plusone" 11 android:layout_width="fill_parent" 12 android:layout_height="wrap_content" 13 android:inputType="none" /> 14 15 <TextView 16 android:id="@+id/symbol" 17 android:layout_width="fill_parent" 18 android:layout_height="wrap_content" /> 19 20 <EditText 21 android:id="@+id/plustwo" 22 android:layout_width="fill_parent" 23 android:layout_height="wrap_content" 24 android:inputType="none" /> 25 26 <Button 27 android:id="@+id/count" 28 android:layout_width="fill_parent" 29 android:layout_height="wrap_content" /> 30 31 </LinearLayout>