在AndroidManifast注册activity,欲想运行一个Activity,得先注册
android:name=".FirstActivity"
android:label="This is my first Activity" //标题栏
>
//让FirstActivity,作为主Activity
===========
Toast的应用
Toast.makeText(FirstActivity.this, "show Toast", Toast.LENGTH_LONG).show();
//.makeText返回Toast对象,再调用show方法
FirstActivity.this,在哪个Activity显示
====================
启动第二个Activity
先注册Activity:
android:name=".SecondActivity" //类名
>
//点击button,启动另外一个Activity
class Listener2 implements OnClickListener{
@Override
public void onClick(View v) {
//FirstActivity.this,当前的Activity
//SecondActivity.class,想要启动的Activity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);//启动Activity
}
==========================
用Intent,指定Android内置的动作
Intent intent = new Intent(Intent.ACTION_DIAL);//指定Intent,打电话
//指定Intent对象要操作的数据
//一般通过字符串传送,由Uri解析
intent.setData(Uri.parse("tel:10086"));
startActivity(intent);//启动Activity
=========================
向下一个Activity传递数据
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
String data="1234qwer";
//向下一个Activity传递数据
//key,键;data,值
intent.putExtra("key", data);
startActivity(intent);
}
//得到传递过来的数据
//获得当前Activity的Intent
Intent intent = getIntent();
String string = intent.getStringExtra("key");//得到传递过来的数据
Log.d("SecondActivity", string);
Toast.makeText(SecondActivity.this, string, Toast.LENGTH_LONG).show();
==========================
返回数据给上一个Activity
step1
public void onClick(View v) {
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivityForResult(intent, 1);// 返回数据给上一个Activity
}
step2
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("key1", "value1");
setResult(RESULT_OK, intent);//向上一个Activity,返回数据
finish();//销毁Activity
}
step3
//复写
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
String string = data.getStringExtra("key1");
Log.d("SecondActivity", string);
}
break;
default:
break;
}
}
================================
知晓当前是在哪个Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//获取当前实例的类名
//并通过log打印出来
Log.d("MainActivity", getClass().getSimpleName());
}