startActivityForResult基本用法

对于初学者,如果一个界面A跳到界面B,B要返回数据,很多喜欢在OnResume 里刷新界面,这是不科学的,应该用startActivityForResult,对于新启动的界面要返回数据的话,这样做才是合理的。传参requestCode ,代表你的请求码,返回的时候用来判断是不是你要求返回的数据。第二个界面(就是你启动的界面)在关闭之前要做setResult(RESULT _OK,intent),intent里放入你要返回的数据。最后在开始界面(第一个界面)回调onActivityResult,拿到返回数据,刷新即可。代码如下: 
 

xml:activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
   >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="startActivity"
        android:text="传值" />

</RelativeLayout>
第一个界面:

public class MainActivity extends ActionBarActivity {

	private TextView returnText ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		returnText = (TextView)findViewById(R.id.text);
		

	}

	public void startActivity(View view) {
		startActivityForResult(new Intent(MainActivity.this,
				SecondActivity.class), 1);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode)
		{
		case 1:
				if(resultCode == RESULT_OK)
				{
					String returnData = data.getStringExtra("return");
					returnText.setText(returnData);
				}
				break;
		}
		
	}

}

第二个界面:

public class SecondActivity extends Activity {
	
	private TextView returnText ;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.activity_main);
	    returnText = (TextView)findViewById(R.id.text);
	    returnText.setText("return");
	}
	
	public void startActivity(View view)
	{
		Intent intent = new Intent();
		intent.putExtra("return", "I love you !");
		setResult(RESULT_OK,intent);
		finish();
		
	}

}

最后记得在manifest文件注册SecondActivity就好了。

你可能感兴趣的:(android)