我想创建一个小部件应用,添加后会启动ConfigurationActivity
,其中有一些选项可供选择。
然后,您可以点击Next
按钮转到NextActivity
并配置您在第一个屏幕上选择的每个选项。
然后,单击Finish
按钮并返回主屏幕,其中包含小部件。
可以通过我在XML中定义的配置活动来完成,或者我是否必须在startActivity
中执行onEnabled()
,然后以这种方式更新我的小部件?
感谢您的帮助。
答案 0 :(得分:3)
您可以通过在xml中定义的配置活动完全执行此操作。只需让您的第一个活动启动一个转到第二个活动的意图,但使用startActivityForResult()方法。然后在第二个活动中,当用户单击第二个活动中的“完成”按钮时,将其设置为第二个活动调用finish()
方法。但在调用完成之前,请将结果设置为您在第二个活动中收集的所有数据。然后,控制将返回到第一个活动,您可以在onActivityResult()
方法中处理从第二个活动中获得的结果。然后,只需将第二个活动的结果添加到您将从此活动返回的结果中。
好吧,让我们来看看这个准系统的例子。
ConfigActivity1 extends Activity{
protected onCreate(Bundle icicle){
//do your setup stuff here.
//This is the button that's going to take us to the next Config activity.
final Button nextConfig = (Button)findViewById(R.id.next_config);
//We'll add an onClickListener to take us to the second config activity
nextConfig.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
//Construct Intent to launch second activity
Intent furtherConfigIntent = new Intent(ConfigActivity1.this, ConfigActivity2.class);
//By using startActivityForResult, when the second activity finishes it will return to
//this activity with the results of that activity.
startActivityForResult(furtherConfigIntent, 0);
}
});
//finish any other setup in onCreate
}
//This is a callback that will get called when returning from any activity we started with the
//startActivityForResult method
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(resultCode == Activity.RESULT_CANCELED){
//this means the second activity wasn't successfull we should probably just
//return from this method and let the user keep configuring.
return;
}
//ok, if we made it here, then everything went well in the second activity.
//Now extract the data from the data Intent, compile it with the results from this
//acitivity, and return them. Let's say you put them in an Intent called resultsIntent.
setResult(Activity.RESULTS_OK, resultsIntent);
finish();
}
}
第二次活动将非常简单。只需收集配置数据,当用户按下完成后,将结果数据和resultCode设置为OK,然后完成。