Create a WebView without xml

廉价感情. 提交于 2020-03-26 04:09:21

问题


For some reason (like loading and don't think too long) i need to create by code a web view and show it after 2s not immediately i have a pointer to my context. i have a id for my relative layout.

I have try some code but i see nothing i don't know if it's the position who is bad or the view.

So what is the good way to make a simple web View who match_parent without any XML? any sample somewhere?

what i have try (i know it's not in match parent it's a test or see the limite of the view if she exist but i see nothing)

web = new WebView(context);
web.setLayoutParams(new LayoutParams(200, 200));
web.setX(400);
web.setY(400);
web.bringToFront(); 

My xml the thing i didn't find is how to say i add my webview in this layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >    
</RelativeLayout>

回答1:


You need to add it to your root view. It's created but floating around unattached to any view.

RelativeLayout main = (RelativeLayout) findViewById(R.id.main);

WebView web = new WebView(context);
web.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 
    LayoutParams.MATCH_PARENT));

main.addView(web); // <--- Key line



回答2:


final WebView wv = new WebView(main);
new AsyncTask<Void,Void,Void>(){
    @Override
    protected Void doInBackground(Void... params) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex){
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        mainLayout.addView(wv);
        LayoutParams params = wv.getLayoutParams();
        // Edit those params as you need, then call
        wv.setLayoutParams(params);
    }   

}.execute();


来源:https://stackoverflow.com/questions/17018960/create-a-webview-without-xml

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