intent.putExtra()方法參數詳解


【putExtra("A",B)中,AB為鍵值對,第一個參數為鍵名,第二個參數為鍵對應的值。順便提一下,如果想取出Intent對象中的這些值,需要在你的另一個Activity中用getXXXXXExtra方法,注意需要使用對應類型的方法,參數為鍵名】

要不我舉個例子吧,,大家注意注釋的地方哈,源碼在下面。

來建第一個Activity:MyIntent

public class MyIntent extends Activity {
          
        /*聲明控件對象*/
        private EditText et1, et2;
        private Button   bt;
          
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
          
        /*取得控件對象*/
        et1 = (EditText) findViewById(R.id.et1);
        et2 = (EditText) findViewById(R.id.et2);
        bt = (Button) findViewById(R.id.bt);
          
  
        /*為按鈕綁定監聽器*/
        bt.setOnClickListener(new OnClickListener() {
                          
                        @Override
                        public void onClick(View v) {
                                /*取得輸入框中的內容*/
                        String et1Str = et1.getText().toString();
                        String et2Str = et2.getText().toString();
                        //創建Intent對象,參數分別為上下文,要跳轉的Activity類
                        Intent intent = new Intent(MyIntent.this, SecondActivity.class);
                        //將要傳遞的值附加到Intent對象
                        intent.putExtra("et1", et1Str);
                        intent.putExtra("et2", et2Str);
                        //啟動該Intent對象,實現跳轉
                        startActivity(intent);
                        }
                });
          
          
          
    }
}

再建第二個Activity:SecondActivity

public class SecondActivity extends Activity{
          
        //聲明TextView對象
        private TextView tv;
  
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.second);
                  
                //取得TextView對象
                tv = (TextView) findViewById(R.id.tv);
                  
                //取得啟動該Activity的Intent對象
                Intent intent =getIntent();
                /*取出Intent中附加的數據*/
                String first = intent.getStringExtra("et1");
                String second = intent.getStringExtra("et2");
                  
                //計算得到結果
                int result = Integer.parseInt(first) + Integer.parseInt(second);
                  
                //設置TextView顯示的文本
                tv.setText("計算結果為:"+String.valueOf(result));
                  
                  
        }
          
}








免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM