Activity(2. 跳转)

Activity的跳转有两种方式:

  • 普通跳转:
Intent intent = new Intent(MainActivity.this, SecondActivty.class);

startActivity(intent);
  • 带返回值的跳转:
    • 调用startActivityForResult,参数带请求索引
public static final int REQUEST_SEC = 1; //请求的ID



Intent backIntent = new Intent(MainActivity.this, SecondActivty.class);

startActivityForResult(backIntent, REQUEST_SEC);
    • 接收端Activity处理该跳转请求
Intent intent = new Intent();

intent.putExtra("value", "hello word");

intent.putExtra("input", MainActivity.REQUEST_SEC);

setResult(RESULT_BACK,intent);

finish();//返回前调用finish,销毁本activity,类似于back
    • 在MainActivity中处理返回
    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        // TODO Auto-generated method stub

        super.onActivityResult(requestCode, resultCode, data);

        

        Log.i(TAG_ACTIVITY, "requestCode:" + requestCode);

        Log.i(TAG_ACTIVITY, "resultCode:"  + resultCode);

        

        if(resultCode == SecondActivty.RESULT_BACK && REQUEST_SEC == requestCode){

            Toast.makeText(getApplicationContext(), data.getStringExtra("value"),

                     Toast.LENGTH_SHORT).show();

        }

    }

 

你可能感兴趣的:(Activity)