Skip to content Skip to sidebar Skip to footer

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.

public class MyApp extends Application
{
    public WebView _WebView = null;

    @Override
    public void onCreate()
    {
        _WebView = new WebView(getApplicationContext());
        // Settings etc.
        _WebView.loadUrl("url");

        super.onCreate();
    }
}

Remove the view from main.xml.

public class MyActivity extends Activity
{
    WebView _WebView;
    RelativeLayout _Layout; // Should be declared in main.xml.

    /** Called when the activity is first created. */
    @Override
    public void onCreate(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);
        ViewTreeObserver vto = _Layout.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new MyLayoutListener()); // .layout(0,0,width,height);

        Display display = getWindowManager().getDefaultDisplay();
        MyApp app = (MyApp) this.getApplication();
        _WebView = app._WebView;
        _Layout.addView(_WebView, display.getWidth(), display.getHeight());
    }

    @Override
    protected void onDestroy()
    {
        _Layout.removeView(_WebView);
        super.onDestroy();
    }
}

private class MyLayoutListener implements OnGlobalLayoutListener
{
    public void onGlobalLayout()
    {
        Display display = 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"