Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> Activity獲取返回值,activity返回值

Activity獲取返回值,activity返回值

編輯:關於android開發

Activity獲取返回值,activity返回值


public class MainActivity extends Activity {

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

    public void click(View c){
        //跳轉至選擇聯系人Activity
        Intent intent = new Intent(this, ContactActivity.class);
//        startActivity(intent);
        //用這個api啟動的Activity,在銷毀時,系統會回調onActivityResult
        startActivityForResult(intent, 10);
    }
    
    
    //如果有Activity在銷毀時返回了數據,那麼就會調用此方法來接收數據
    //requestCode:用來區分數據來自於哪一個Activity
    //resultCode:用來區分返回的數據是什麼類型的
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        
        String name = data.getStringExtra("name");
        if(requestCode == 10){
            EditText et = (EditText)findViewById(R.id.et);
            et.setText(name);
        }
        
    }
    

}
public class ContactActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        
        ListView lv = (ListView) findViewById(R.id.lv);
        
        final String[] objects = new String[]{
                "小志",
                "逼哥",
                "世界級XXX",
                "國服第一"
        };
        
        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv, objects));
    
        //給listview設置條目的點擊偵聽
        lv.setOnItemClickListener(new OnItemClickListener() {

            //當某個條目被點擊時,此方法調用
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                
                //Activity返回時傳遞數據,也是通過意圖對象
                Intent data = new Intent();
                //把要傳遞的數據封裝至意圖對象中
                data.putExtra("name", objects[position]);
                
                //當前Activity銷毀時,data這個意圖就會傳遞給啟動當前Activity的那個Activity
                setResult(1, data);
                
                //銷毀當前Activity
                finish();
            }
        });
    }
    
    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();
    }
}

 

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