Reputation: 3703
In my application i'm using customized window title. and on back pressed i'm calling oncreate method of same activity.i'm getting following exception how can i call oncreate method of same activity onbackpressed-
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
code is-
private Bundle mBundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
mBundle=savedInstanceState;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
.
.
.
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
if(backFlag){
onCreate(mBundle);
backFlag=false;
}else{
finish();
}
}
Answer- I got solution for the problem. on backpressed i'm calling same activity again
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
//super.onBackPressed();
if(backFlag){
backFlag=false;
Intent i=new Intent(this,MainActivity.class);
startActivity(i);
finish();
}else{
finish();
}
}
Upvotes: 0
Views: 2085
Reputation: 14590
Its not because of the order of calling methods in onCreate()
..You are getting this exception because of this line..
if(backFlag){
onCreate(mBundle);
backFlag=false;
}else{
finish();
}
when you backpressd you are agin calling onCreate() method of the activity It will try again call the requestWindowFeature()
but all the views alreay added so its gives you a exception remove onCreate()
from onBackPressed()
then it will work fine.
If you dont want to close your activity onBackpressed dont call super.onBackpressed
thats it..
Update like this..
if(backFlag){
backFlag=false;
}else{
finish();
}
Upvotes: 1
Reputation: 128428
requestFeature() must be called before adding content
=> Exception itself suggest you that Don't call requestFeature()
before adding content (i.e. setContentView()
)
Now, Issue is at this point:
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
Solution:
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
setContentView(R.layout.activity_main);
One more thing, why do you need to call onCreate()
again in onBackKeyPressed()
?
Upvotes: 1
Reputation: 7415
Change your onCreate()
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBundle=savedInstanceState;
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
.
.
.
}
Upvotes: 1
Reputation: 989
Move this line
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_title);
above
setContentView(....);
Upvotes: 1