我们有一个Webservice类,它将WebserviceListener作为该特定Web服务调用的回调。我的问题是Android可以重新创建我的Activity(方向更改等等),然后我在该回调中有旧的引用。当我尝试设置视图的可见性,或将我的隐藏标志设置为vai saveInstanceState
方法时,它们都被重新创建。我该如何解决这个问题?
我的代码:
public class UploadActivity extends Activity implements {
private Button mButton;
private volatile boolean mHidden;
private class UploadWSListener extends WebServiceAdapter {
@Override
public void onComplete(Bundle bundle) {
mSuggestion = (Suggestion) bundle.getSerializable(WebService.BUNDLE_DATA);
if (mSuggestion.isAutomatic()) {
myHandler.sendEmptyMessage(1);
}
else {
myHandler.sendEmptyMessage(0);
}
}
@Override
public void onServerError(ErrorResult error, Bundle bundle) {
onError(error.getDebugInfo());
}
@Override
public void onError(WebServiceException wse, Bundle bundle) {
onError(wse.getMessage());
}
private void onError(String message) {
Log.w(TAG, "Error downloading suggestions. Error: " + message);
myHandler.sendEmptyMessage(-1);
}
}
private class PhotoUploadHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Handler is ivoked. What: " + msg.what);
switch (msg.what) {
case 0:
mButton.setText("Upload");
break;
case 1:
mButton.setVisibility(View.GONE);
mHidden = true;
break;
case -1:
Toast.makeText(PhotoUploadActivity.this, "Network error", Toast.LENGTH_LONG).show();
finish();
break;
}
Log.i(TAG, "Handler with " + msg.what + " run.");
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.i(TAG, "onSaveInstanceState hidden:" + mHidden);
super.onSaveInstanceState(outState);
// outState.putBoolean("hide", mButton.getVisibility() == View.GONE);
outState.putBoolean("hide", mHidden);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null && savedInstanceState.getBoolean("hide")) {
mButton.setVisibility(View.GONE);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myHandler = new UploadHandler();
Model model = Model.instance(getApplicationContext());
WebService service = model.getWebService();
if (Model.u) {
Model.u = false;
service.getSuggestions(new UploadWSListener(), Prefs.getUserToken(getApplicationContext()), getLatitude(),getLongitude(), getAltitude());
}
}
}
我的主要问题:
findViewByID
获取它们,那么它是否智能?答案 0 :(得分:0)
我认为您需要一种方法来向监听器注册您的活动,这样您可以通过取消注册活动并在创建新活动时再次注册它来对方向更改做出反应。据我所知,在破坏和娱乐之间,所有对“旧”活动的调用都将被保留,直到创建新活动为止。
在您的活动中持有视图是可以的,因为当您的活动被销毁时它们将被释放/破坏。如果您必须多次访问它们,可以将它们作为类成员保存,因为当您的布局结构非常深时,通过findViewByID()获取它们可能会很昂贵。