setContentView() is not enough to switch between layouts?

我们两清 提交于 2020-01-11 10:27:28

问题


I have 2 layouts.

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

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

The switching seems to occur but the webview is blank.

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


回答1:


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

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.




回答2:


I use this method: In main program:

private LinearLayout mainview;
private LinearLayout playerview;

In onCreate:

LayoutInflater inflater = LayoutInflater.from(this);
setContentView(R.layout.main);
mainview = (LinearLayout) this.findViewById(R.id.main);
playerview = (LinearLayout) inflater.inflate(R.layout.player, null);

Then you can call

setContentView(mainview);

and

setContentView(playerview);

whenever you want. All you need is two layout xml files, one for each layout. This is much simpler than Fragments or other methods.

For some reason, I don't have to inflate the main view I start with, only the others. I think it's because setContentView() must inflate the view for you when it's called.



来源:https://stackoverflow.com/questions/11605437/setcontentview-is-not-enough-to-switch-between-layouts

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!