Android學習之Intent使用

1、使用顯示Intent

Intent intent = new Intent(FirstActivity.this,SecondActivity.class);

startActivity(intent);

上述代碼的作用是打開活動SecondActivity

2、使用隱式Intent

首先打開AndroidManifest.xml,添加代碼:

<activity
android:name="com.example.activitytest.SecondActivity"
android:label="@string/title_activity_second" >
<intent-filter>
<action android:name="com.example.activitytest.ACTION_START" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="com.example.activitytest.MY_CATEGORY" />
</intent-filter>
</activity>

然後修改FirstActivity中按鈕的點擊事件:

btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent=new Intent("com.example.activitytest.ACTION_START");

intent.addCategory("com.example.activitytest.MY_CATEGORY");

startActivity(intent);
}
});

還可以使用隱式Intent,啓動其他程序的活動。

Intent intent=new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://www.cnblogs.com/zhouhb/"));
//Intent intent=new Intent(Intent.ACTION_DIAL);
//intent.setData(Uri.parse("tel:12345"));

3、使用Intent在Activity之間傳遞數據

3.1 從FirstActivity向SecondActivity傳遞數據

String s="from first";
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("data", s);
startActivityForResult(intent, 1);

3.2 SecondActivity接收傳遞來的數據

Button btn=(Button)findViewById(R.id.button2);
Intent intent=getIntent();
String string=intent.getStringExtra("data");
btn.setText(string);

3.3 SecondActivity向FirstActivity返回數據

btn.setOnClickListener(new OnClickListener() { 
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
returnData();
}
});

private void returnData() {
Intent intent=new Intent();
intent.putExtra("returnData", "from Second");
setResult(RESULT_OK,intent);
finish();
}

//如果用戶不是通過點擊按鈕,而是按下Back鍵回到FirstActivity,則重寫 onBackPressed

public void onBackPressed() {
// TODO Auto-generated method stub
returnData();
}

3.4 在FirstActivity中重寫onActivityResult得到SecondActivity返回的數據

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch (requestCode) {
  case 1:
    if(resultCode==RESULT_OK){
      String string=data.getStringExtra("returnData");
      Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
    }
    break;

  default:
  break;
  }

}


轉自:寂寞沙洲

發佈了13 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章