Android(4.Activity的基本控件)

来源:互联网 发布:海上大作战修改数据 编辑:程序博客网 时间:2024/05/07 05:38

Activity中的控件:TextView,EditText,Button,Menu,

过程:1.声明控件 2.为控件设置值 3.创建监听器 4.将监听器绑定到按钮点击事件上

简单的计算器例子:

Activity02:

 public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //根据id取得控件的对象        factorOne=(EditText) findViewById(R.id.factorOne);        factorTwo=(EditText) findViewById(R.id.factorTwo);        symbol=(TextView) findViewById(R.id.symbol);        calculate=(Button)findViewById(R.id.calculate);        //显示值        symbol.setText(R.string.symbol);        calculate.setText(R.string.calculate);        //绑定监听器        calculate.setOnClickListener(new CalculateListener());    }
//监听器    class CalculateListener implements OnClickListener{@Overridepublic void onClick(View arg0) {//取得EditText控件的值String factorOneStr=factorOne.getText().toString();String factorTwoStr=factorTwo.getText().toString();//将值存放到Intent对象中Intent intent=new Intent();intent.putExtra("factorone", factorOneStr);intent.putExtra("factortwo", factorTwoStr);//使用Intent对象启动Activity对象intent.setClass(Activity02.this,ActivityResult.class);Activity02.this.startActivity(intent);}    }

ActivityResult:

protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.result);resultView=(TextView) findViewById(R.id.resultView);backButton=(Button) findViewById(R.id.backButton);backButton.setText(R.string.back);//接收Intent对象中的传递的值Intent intent=getIntent();String factorOneStr=intent.getStringExtra("factorone");String factorTwoStr=intent.getStringExtra("factortwo");//计算int result=Integer.parseInt(factorOneStr)*Integer.parseInt(factorTwoStr);resultView.setText(result+"");backButton.setOnClickListener(new backButtonListener());}