- 您可以使用对话框。
- 您用于启动活动的意图可以保存正在启动的活动可访问的原始数据。然后,您可以有条件地使用控件填充已启动的活动。毕竟,您可以将结果返回给第一个活动。
以指定模式启动活动的代码片段(模式常量定义如下):
public class SettingsActivity extends Activity
{
public static final String EXTRA_MODE = "your_mode_extra_name";
public static final int MODE_AGE = 0;
public static final int MODE_GENDER = 1;
private static final int MODE_DEFAULT = MODE_AGE;
@Override
public void onCreate(Bundle savedInstance)
{
int mode = getIntent().getIntExtra(EXTRA_MODE, MODE_DEFAULT);
switch(mode)
{
case MODE_AGE:
setContentView(R.layout.age_mode_layout);
//TODO: find controls by ID and set their event handlers here
break;
case MODE_GENDER:
setContentView(R.layout.age_mode_gender);
//TODO: find controls by ID and set their event handlers here
break;
}
}
}
返回性别的代码片段:
public class SettingsActivity extends Activity
{
public static final String EXTRA_GENDER = "your_gender_extra_name";
public static final int GENDER_FEMALE = 0;
public static final int GENDER_MALE = 1;
private void returnGender(int gender)
{
setResult(RESULT_OK, new Intent().putExtra(EXTRA_GENDER, gender));
finish();
}
}
最后显示设置活动并返回结果:
public class MainActivity extends Activity
{
//actually we could use mode constants from SettingsActivity;
//just to show that generally this is separate constants set
private static final int ID_AGE = 0;
private static final int ID_GENDER = 1;
private void requestAge()
{
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
intent.putExtra(SettingsActivity.EXTRA_MODE, SettingsActivity.MODE_AGE);
startActivityForResult(intent, ID_AGE);
}
private void requestGender()
{
Intent intent = new Intent(getApplicationContext(), SettingsActivity.class);
intent.putExtra(SettingsActivity.EXTRA_MODE, SettingsActivity.MODE_GENDER);
startActivityForResult(intent, ID_GENDER);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK)
return; //something went wrong
switch(requestCode)
{
case ID_GENDER:
int gender = data.getIntExtra(SettingsActivity.EXTRA_GENDER, -66666);
//you've got the gender, use it
break;
case ID_AGE:
//get age from the intent and use it
break;
}
}
}