Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android_06_Activity跳轉時,數據的傳遞及接收

Android_06_Activity跳轉時,數據的傳遞及接收

編輯:關於Android編程

MainActivity.java

 

package com.itheima.senddata;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void click(View v){
	//這也是一種啟動方式,把兩步寫成了一步;
    	Intent intent = new Intent(this, SecondActivity.class);
    	//方法一:將數據直接封裝進意圖對象中
    	//把數據封裝至intent對象中
//    	intent.putExtra(malename, 李志);
//    	intent.putExtra(femalename, 芙蓉姐姐);
    	
    	//方法二:先將數據封裝進bundle對象,然後//把bundle對象封裝至intent對象中
    	//把數據封裝至bundle對象中
    	Bundle bundle = new Bundle();
    	bundle.putString(malename, 李志);
    	bundle.putString(femalename, 芙蓉姐姐);
    	//把bundle對象封裝至intent對象中
    	intent.putExtras(bundle);
    	startActivity(intent);
    }
    
}

SecondActivity.java

 

 

package com.itheima.senddata;

import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_second);
		
		Intent intent = getIntent();
		//數據怎麼封裝的,那麼取時,就對應地去取
		//從intent對象中把封裝好的數據取出來
//		String maleName = intent.getStringExtra(malename);
//		String feMaleName = intent.getStringExtra(femalename);
		
		Bundle bundle = intent.getExtras();
		String maleName = bundle.getString(malename);
		String feMaleName = bundle.getString(femalename);
		
		Random rd = new Random();
		int yinyuan = rd.nextInt(100);
		
		TextView tv = (TextView) findViewById(R.id.tv);
		tv.setText(maleName + 和 + feMaleName + 的姻緣值為 + yinyuan);
	}
}

 
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved