putExtra方法


【開篇罵幾句:fuck】
1.扯淡intent.putExtra()怎么使用?
2.胡說intent.putExtra();

【扯淡:其實你在問它怎么用的時候,你要明白,你知道不知道這是個什么東東,有必要問嗎?有?我猜你已經知道它的基本概念了,它是用來傳參數的對不對,是的,就這么簡單。但你仍然在網上百度它怎么用,我不理解你為啥要這么做,哦,我又猜到了,我猜啊,你是不知道他的具體參數是怎么個用吧,對了,問題的核心來了,所有安卓開發中的問題都是方法參數的問題】

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


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

來建第一個Activity:MyIntent 
[mw_shl_code=java,true]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);
                        }
                });
        
        
        
    }
}[/mw_shl_code]

再建第二個Activity:SecondActivity 
[mw_shl_code=java,true]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));
                
                
        }
        
}
[/mw_shl_code]


免責聲明!

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



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