将Android视图附加/分离到布局

时间:2012-05-08 19:41:05

标签: android android-layout android-webview

我想在Application类的衍生物的onCreate()方法中创建WebView,然后在调用onCreate()活动时将其附加到主布局,并在调用onDestroyed()时将其分离。因此,每次创建/销毁活动时,WebView组件都是相同的(有点单例)。问题是我(使用我的Windows API背景)没有想法如何做到这一点。只是新的WebView()/ addiew()/ removeView()?

你问我为什么要这样做? Prevent Android activity from being recreated on turning screen off简而言之,WebView永远不应该被销毁。

1 个答案:

答案 0 :(得分:2)

没什么特别的。在清单中将MyApp注册为应用程序类名称。

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

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

        super.onCreate();
    }
}

从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);
    }
}