意图的用途一般是连接活动,传递数据,从意图返回数据等,下面的例子就是利用意图来交互MainActivity和SecondActivity这两个活动。
效果图如下:
实现代码如下:
MainActivity类代码:
package com.example.usingintent; import android.R.integer;
import android.app.Activity;
import android.app.LauncherActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast; public class MainActivity extends Activity {
int request_Code = 1;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
} public void onClick(View v){
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
public void onClick2(View v){
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent, request_Code); }
public void onClick3(View v){
Intent intent = new Intent("com.example.usingintent.SecondActivity");
intent.putExtra("str1", "This is string 1");
intent.putExtra("age1", 24); Bundle bundle = new Bundle();
bundle.putString("str2", "This is string 2");
bundle.putInt("age2", 48);
intent.putExtras(bundle); startActivityForResult(intent, request_Code); } @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == request_Code){
if(resultCode==RESULT_OK){
Toast.makeText(this, data.getData().toString(), Toast.LENGTH_SHORT).show();
}else if(resultCode == 24){
Toast.makeText(this, Integer.toString(data.getIntExtra("age3", 1)), Toast.LENGTH_SHORT).show();
Toast.makeText(this, data.getData().toString(), Toast.LENGTH_SHORT).show();
}
}
} }
SecondActivity类代码:
package com.example.usingintent; import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast; public class SecondActivity extends Activity {
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.second); //获取传递过来的数据
Toast.makeText(this, getIntent().getStringExtra("str1"), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Integer.toString(getIntent().getIntExtra("age1",0)), Toast.LENGTH_SHORT).show(); Bundle bundle = getIntent().getExtras();
Toast.makeText(this, bundle.getString("str2"), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Integer.toString(bundle.getInt("age2")), Toast.LENGTH_SHORT).show(); }
public void onClick(View v) {
Intent data = new Intent();
EditText editText = (EditText)findViewById(R.id.txt_username); data.setData(Uri.parse(editText.getText().toString()));
setResult(RESULT_OK, data); //destroy current activity
finish();
}
public void onClick2(View v) {
Intent intent = new Intent();
//返回数据
intent.putExtra("age3", 45);
intent.setData(Uri.parse("something pass back to main activity"));
setResult(24, intent); //destroy current activity
finish();
}
}