的setContentView()是不够的布局之间进行切换?布局、setContentView

2023-09-07 15:51:34 作者:一个人习惯了发呆

我有2个布局。

第1负载(一个web视图)在程序启动时的罚款。

The 1st loads (a WebView) fine when the program starts.

注:第二个也负载(一个简单的布局)的罚款,当用户选择一个菜单项:

The 2nd one also loads (a simple layout) fine when user selects a menu item:

setContentView(R.layout.simple);
LinearLayout ll = (LinearLayout) findViewById(R.id.simple_layout);

它所做的就是显示图像,同时处理一些背景。当处理完成后,它将尝试切换回(通过处理程序),以它只是遮蔽了的WebView。

All it does is display an image while processing something in the background. When processing is done, it attempts to switch back (via Handler) to the WebView it just obscured.

setContentView(R.layout.main);

切换似乎发生,但web视图是空白

这是为什么?是不是的setContentView()足以切换回第一个布局就像切换到第二个能正常工作?

Why is that? Isn't setContentView() enough to switch back to the 1st layout just as the switch to 2nd worked fine?

推荐答案

这里的主要问题是,你不应该调用的setContentView()多次(如在评论中指出的)。片段是一个不错的主意,但你也可以使用 ViewFlipper 如果你的刚刚追平2次之间切换。 例如取自 http://blog.kerul.net/2011/ 07 / viewflipper-照例a-简单flashcard.html

The main problem here is that you shouldn't call setContentView() several times (as noted in the comments). Fragments are a good idea, but you can also use a ViewFlipper if your just tying to change between 2 views. Example taken from http://blog.kerul.net/2011/07/viewflipper-examplea-simple-flashcard.html

   Button next,previous;
    ViewFlipper vf;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        next = (Button) findViewById(R.id.Button01);
        previous = (Button) findViewById(R.id.Button02);
        next.setOnClickListener(this);
        previous.setOnClickListener(this);
        vf=(ViewFlipper)findViewById(R.id.ViewFlipper01);
    }

    //@Override
    public void onClick(View v) {
        if (v == next) {
            vf.showNext();
        }
        if (v == previous) {
            vf.showPrevious();
        }
    }
}

的原因,你的屏幕是空白的,因为你将不得不再次重新初始化你的WebView。如果你要调用的setContentView()几次,你必须重新获得您findViewByIds和所有。列表视图包括在内。

The reason your screen is blank is because you'll have to re-init your webview again. If you were to call setContentView() several times, you have to re get your findViewByIds and all that. List view included.