Attach/detach Android View To/from Layout
I want to create a WebView in onCreate() method of a derivative of Application class, then attach it to the main layout when an activity onCreate() is called and detach it when onD
Solution 1:
Nothing special. Register MyApp as application class name in the manifest.
publicclassMyAppextendsApplication
{
publicWebView_WebView=null;
@OverridepublicvoidonCreate()
{
_WebView = newWebView(getApplicationContext());
// Settings etc.
_WebView.loadUrl("url");
super.onCreate();
}
}
Remove the view from main.xml.
publicclassMyActivityextendsActivity
{
WebView _WebView;
RelativeLayout _Layout; // Should be declared in main.xml./** Called when the activity is first created. */@OverridepublicvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
_Layout = (RelativeLayout) findViewById(R.id.rl);
ViewTreeObservervto= _Layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(newMyLayoutListener()); // .layout(0,0,width,height);Displaydisplay= getWindowManager().getDefaultDisplay();
MyAppapp= (MyApp) this.getApplication();
_WebView = app._WebView;
_Layout.addView(_WebView, display.getWidth(), display.getHeight());
}
@OverrideprotectedvoidonDestroy()
{
_Layout.removeView(_WebView);
super.onDestroy();
}
}
privateclassMyLayoutListenerimplementsOnGlobalLayoutListener
{
publicvoidonGlobalLayout()
{
Displaydisplay= getWindowManager().getDefaultDisplay();
_WebView.layout(0, 0, display.getWidth(), display.getHeight());
//_Layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
Post a Comment for "Attach/detach Android View To/from Layout"