Intent使用,intent

來源:互聯網
上載者:User

Intent使用,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;
  }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.