Jebik
Jebik

Reputation: 788

Create a WebView without xml

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>

Upvotes: 1

Views: 5598

Answers (2)

Ken Wolf
Ken Wolf

Reputation: 23269

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

Upvotes: 4

Charlie-Blake
Charlie-Blake

Reputation: 11050

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

Upvotes: 0

Related Questions