Android四大组件之Intent

Intent可以理解为意图,用来协助完成Android各个组件之间的通讯

Intent实现跳转:

1>跳转不返回数据

2>跳转返回数据

案例:intent实现不同activity跳转

1.新建一个activity

public class otherActivity extends AppCompatActivity {

@Override

    protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

Log.i("匿名内部类","点击事件2");

}

}

2.注册新activity

打开AndroidManifest.xml,新建,不新建activity程序会崩溃

 

3.mainactivty中添加代码

public class MainActivity extends AppCompatActivity {

@Override

    protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button bt = (Button) findViewById(R.id.button);

//1.匿名内部类

        bt.setOnClickListener(new View.OnClickListener() {

@Override

            public void onClick(View view) {

Log.i("匿名内部类","点击事件");

Intent intent=new Intent(MainActivity.this,otherActivity.class);//注意由于在内部类中,无法直接用this

startActivity(intent);

}

});

}

}

Intent传值:

传送方->接受方:

传送方:

Intent intent=new Intent(MainActivity.this,otherActivity.class);

intent.putExtra("name","yanhe");

startActivity(intent);

接受方:

Intent intent = getIntent();  

String string = intent.getStringExtra("name");

接受方->传送方:

传送方:

Intent intent=new Intent(MainActivity.this,otherActivity.class);

intent.putExtra("name","yanhe");

  startActivityForResult(intent,1); ////判断requestCode和resultCode的值便可以确定是哪个Activity回传回来的数据

实现方法-protected void onActivityResult(int requestCode,int resultCode,@Nullable Intent data);

接受方:

public boolean onKeyDown(int keyCode, KeyEvent event) {

//按下返回键会触发

Intent intent =new Intent();

intent.putExtra("key","wudi");

setResult(2,intent);

finish();

return super.onKeyDown(keyCode, event);

}

你可能感兴趣的:(Android四大组件之Intent)