android安卓开发基础小笔记,添加按钮事件,打开新窗体,窗体传值,回传

时间:2023-03-08 19:51:54

给一个按钮添加onclick事件

        //获取按钮对象
Button Aiyo = (Button)findViewById(R.id.button1);
Aiyo.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {//tv.setText("woceshi");
//弹出提示
Toast.makeText(getApplicationContext(), '你好', Toast.LENGTH_SHORT).show();
}
});

打开新的窗口(activity)

//创建一个窗体对象
Intent newWindow = new Intent();
newWindow.setClass(MainActivity.this, NewWindow.class);
//第一个是当前窗体类,第二个是新窗体类(窗体名称.class)
startActivity(newWindow);
//启动新窗体

当前窗体传值给新窗体

这是当前窗体所做的事情

Intent newWindow = new Intent();
newWindow.setClass(MainActivity.this, NewWindow.class);
//新开窗口传值
Bundle bundle = new Bundle();
bundle.putString("bundleKey", "zongwenlong");
newWindow.putExtras(bundle);
//新开窗口传值 end
//上面的三行赋值的代码其实有点复杂,也可以写成下面的
//新窗口传值1
newWindow.putExtra("key","value");
//新窗口传值1 end
startActivity(newWindow);

新窗体所做的事情

在新窗体的  oncreate 中写

//获取前一个窗体传来的值
Bundle bundle = this.getIntent().getExtras();
Log.e("zllmsg", bundle.getString("bundleKey"));
//获取前一个窗体传来的值end

新窗口关闭,然后将值回传给老窗口

老窗口所做的事情

Intent newWindow = new Intent();
newWindow.setClass(MainActivity.this, NewWindow.class);
//新开窗口传值
Bundle bundle = new Bundle();
bundle.putString("bundleKey", "zongwenlong");
newWindow.putExtras(bundle);
//新开窗口传值 end
//startActivity(newWindow);
startActivityForResult(newWindow, 1111);//这个1111是一个唯一码,还要用到

新窗口所做的事情,写一个按钮事件

Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putString("zllfanhui", "zonglonglongfanhui");
intent.putExtras(bundle);
setResult(1111, intent);
finish();

老窗口又要做事情了,实现一个接口

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Log.e("zllmsg",data.getExtras().getString("zllfanhui"));
}