Attach/detach Android view to/from layout

前端 未结 1 892
终归单人心
终归单人心 2021-01-23 06:14

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

相关标签:
1条回答
  • 2021-01-23 06:33

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题