如何在Android中显示webView并隐藏其他元素

时间:2016-05-03 12:02:49

标签: android webview

我是Android开发的新手,经历了一些使用Eclipse开发Android代码的教程。在这里,我试图在点击按钮后加载带有一些URL的WebView,然后我想隐藏按钮。

我正在使用线性布局。为此,我使用以下代码使其工作,但它没有加载WebView。

public class MainActivity extends ActionBarActivity {

    EditText edit;
    TextView text;
    WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit = (EditText) findViewById(R.id.editText);
        text = (TextView) findViewById(R.id.textView3);
        webView = (WebView) findViewById(R.id.webView1);

        Button b = (Button)findViewById(R.id.button_show);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                String name = edit.getText().toString();
                text.append(name);
                webView.loadUrl("http://www.google.com");
                System.out.println("Loaded Successfully--");
            }
        });
    }

“Loaded Successfully--”消息在控制台中打印,但WebView不可用。

我也试过以下代码,

EditText edit;
TextView text;
WebView webView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    edit = (EditText) findViewById(R.id.editText);
    text = (TextView) findViewById(R.id.textView3);
    webView = (WebView) findViewById(R.id.webView1);

    Button b = (Button)findViewById(R.id.button_show);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            String name = edit.getText().toString();
            text.append(name);
            webView.setWebViewClient(new WebViewClient() {
                @Override
                public boolean shouldOverrideUrlLoading(WebView view,
                        String url) {
                    webView.loadUrl("http://www.google.com");
                    System.out.println("Loaded Successfully--");
                    return true;
                }
            });
        }
    });
}

此次“已成功加载 - ”无法打印。 我在这里缺少什么?

修改

我的XMl文件(activity_main.xml)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="fill"
    tools:context="com.example.asdf.MainActivity" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitXY"
        android:src="@drawable/back" />

   <EditText
       android:id="@+id/editText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/imageView1"
       android:layout_alignLeft="@+id/imageView1"
       android:layout_marginBottom="24dp"
       android:ems="10"
       android:hint="@string/edit_hint"
       android:textColor="#ffffff"
       android:textSize="20dip" >

       <requestFocus />
   </EditText>

   <Button
       android:id="@+id/button_show"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/editText"
       android:layout_alignRight="@+id/imageView1"
       android:text="@string/button_title" />

   <TextView
       android:id="@+id/textView3"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignBottom="@+id/imageView1"
       android:layout_alignLeft="@+id/imageView1"
       android:layout_alignRight="@+id/imageView1"
       android:layout_below="@+id/button_show"
       android:text="@string/edit_hint"
       android:textColor="#ffffff"
       android:textSize="20dip" />

   <TextView
       android:id="@+id/textView2"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_alignParentLeft="true"
       android:layout_centerVertical="true"
       android:gravity="center"
       android:text="As we know the relevant data has been wide-spreaded across various sites under many intentions, factualnote is a type of social software tool in which factual data are brought forward or narrow down to the web users."
       android:textColor="#ffffff"
       android:textSize="20dip"
       android:textStyle="bold" />

   <TextView
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_above="@+id/textView2"
       android:layout_alignParentLeft="true"
       android:layout_marginBottom="22dp"
       android:gravity="center"
       android:text="Factualnote is an web annotation application, which helps the users to mark the specific text, element, page, video, etc in a web page and share it to like-minded people."
       android:textColor="#ffffff"
       android:textSize="20dip"
       android:textStyle="bold" />

</RelativeLayout>

6 个答案:

答案 0 :(得分:1)

尝试这个 在你的onClickListener

edit.setVisibility(View.GONE);
text.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
 b.setVisibility(View.GONE);

答案 1 :(得分:1)

我在这个项目中发现了错误,原因是我错过了在manifest.xml中添加的以下行

days <- as.numeric(gsub('^*([0-9]+)d.*$','\\1',x3))
hours <- as.numeric(gsub('^.*([0-9][0-9])h.*$','\\1',x3))
minutes <- as.numeric(gsub('^.*([0-9][0-9])m.*$','\\1',x4))
seconds <- as.numeric(gsub('^.*([0-9][0-9])s.*$','\\1',x4))
duration_seconds <- seconds + 60*minutes + 60*60*hours + 24*60*60*days

现在没事了。谢谢大家的支持..

答案 2 :(得分:0)

@Ratwanska,您可以使用Intent进行如下所示的URL加载...

 if (Common.isOnline(YourActivity.this)) {
                try {
                    String url = "YOUR URL";
                    Intent i = new Intent(Intent.ACTION_VIEW);
                    i.setData(Uri.parse(url));
                    startActivity(i);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Common.displayToast(YourActivity.this, getResources().getString(R.string.strErrorInternetConnection));
            }

上面的代码将使用Intent在浏览器中打开您指定的链接,您也不必担心隐藏按钮..!

我认为它比使用Webview和隐藏按钮更好。

注意:'Common'是为处理常见内容而创建的自定义类,'isOnline'是该类中用于检查Internet连接的函数。

答案 3 :(得分:0)

您可以使用此方法知道何时加载页面。

mWebview.setWebViewClient(new WebViewClient() {

            boolean error = false;

            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                error = true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                //hide your button
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }
        });


  mWebview.loadUrl(url);

答案 4 :(得分:0)

    webView=(WebView)view.findViewById(R.id.powered_webview);
    webView.setWebViewClient(new MyBrowser());
    webView.getSettings().setLoadsImagesAutomatically(true);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
    webView.loadUrl(AppConstant.POWEREBY_URL);
    return view;
}

    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

答案 5 :(得分:0)

在谷歌下面的代码搜索输入搜索键,当显示键是按下webview开始加载URL并隐藏serch布局。如果用户从webview按Back键,则下一个搜索输入将显示搜索布局。

enter image description here enter image description here

您的活动类应如下所示

package com.example.test;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;

public class MainActivity extends Activity {

    private static final String GOOGLE_SERACH_URL = "https://www.google.com/search?q=";

    private WebView webView;
    private FrameLayout customViewContainer;
    private WebChromeClient.CustomViewCallback customViewCallback;
    private View mCustomView;
    private CustomWebChromeClient mWebChromeClient;
    private CustomWebViewClient mWebViewClient;

    private EditText searchKeyEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        searchKeyEditText = (EditText) findViewById(R.id.editText);
        webView = (WebView) findViewById(R.id.webView1);

        // SetUp WebView
        customViewContainer = (FrameLayout) findViewById(R.id.customViewContainer);

        mWebViewClient = new CustomWebViewClient();
        webView.setWebViewClient(mWebViewClient);

        mWebChromeClient = new CustomWebChromeClient();
        webView.setWebChromeClient(mWebChromeClient);
        webView.getSettings().setJavaScriptEnabled(true);

        // Important for PayUMoney
        webView.getSettings().setDomStorageEnabled(true);

        webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSaveFormData(true);

        Button b = (Button) findViewById(R.id.button_show);

        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                findViewById(R.id.search_layout).setVisibility(View.GONE);

                webView.loadUrl(GOOGLE_SERACH_URL + searchKeyEditText.getText().toString());
            }
        });
    }

    public boolean inCustomView() {
        return (mCustomView != null);
    }

    public void hideCustomView() {
        mWebChromeClient.onHideCustomView();
    }

    @Override
    public void onPause() {
        super.onPause(); // To change body of overridden methods use File |
                            // Settings | File Templates.
        webView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume(); // To change body of overridden methods use File |
                            // Settings | File Templates.
        webView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop(); // To change body of overridden methods use File |
                        // Settings | File Templates.
        if (inCustomView()) {
            hideCustomView();
        }
    }

    class CustomWebChromeClient extends WebChromeClient {
        private View mVideoProgressView;

        @Override
        public void onShowCustomView(View view, int requestedOrientation, CustomViewCallback callback) {
            onShowCustomView(view, callback); // To change body of overridden
                                                // methods use File | Settings |
                                                // File Templates.
        }

        @Override
        public void onShowCustomView(View view, CustomViewCallback callback) {

            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                callback.onCustomViewHidden();
                return;
            }
            mCustomView = view;
            webView.setVisibility(View.GONE);
            customViewContainer.setVisibility(View.VISIBLE);
            customViewContainer.addView(view);
            customViewCallback = callback;
        }

        @Override
        public View getVideoLoadingProgressView() {

            if (mVideoProgressView == null) {
                LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
                mVideoProgressView = inflater.inflate(R.layout.video_progress, null);
            }
            return mVideoProgressView;
        }

        @Override
        public void onHideCustomView() {
            super.onHideCustomView(); // To change body of overridden methods
                                        // use File | Settings | File Templates.
            if (mCustomView == null)
                return;

            webView.setVisibility(View.VISIBLE);
            customViewContainer.setVisibility(View.GONE);

            // Hide the custom view.
            mCustomView.setVisibility(View.GONE);

            // Remove the custom view from its container.
            customViewContainer.removeView(mCustomView);
            customViewCallback.onCustomViewHidden();

            mCustomView = null;
        }
    }

    class CustomWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

        private int webViewPreviousState;

        private final int PAGE_STARTED = 0x1;

        private final int PAGE_REDIRECTED = 0x2;

        Dialog dialog = new Dialog(MainActivity.this);

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewPreviousState = PAGE_STARTED;

            if (dialog == null || !dialog.isShowing())
                dialog = ProgressDialog.show(MainActivity.this, "", "Loading Please Wait", true, true,
                        new OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                // do something
                            }
                        });
        }

        @Override
        public void onPageFinished(WebView view, String url) {

            if (webViewPreviousState == PAGE_STARTED) {
                if (null != dialog)
                    dialog.dismiss();
                dialog = null;
            }

        }
    }

    @Override
    public void onBackPressed() {

        if (findViewById(R.id.search_layout).getVisibility() == View.GONE) {
            findViewById(R.id.search_layout).setVisibility(View.VISIBLE);
        } else {
            super.onBackPressed();
        }

    }
}

主要活动的布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.test.MainActivity1" >

    <LinearLayout
        android:id="@+id/search_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:weightSum="4" >

        <TextView
            android:id="@+id/textView3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Search" />

        <EditText
            android:id="@+id/editText"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2" />

        <Button
            android:id="@+id/button_show"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Show" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/search_layout"
        android:orientation="vertical" >

        <WebView
            android:id="@+id/webView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center" />

        <FrameLayout
            android:id="@+id/customViewContainer"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:visibility="gone" />
    </LinearLayout>

</RelativeLayout>

youtube的帮助程序布局文件,如web内容video_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/progress_indicator"
              android:orientation="vertical"
              android:layout_centerInParent="true"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <ProgressBar android:id="@android:id/progress"
                 style="?android:attr/progressBarStyleLarge"
                 android:layout_gravity="center"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"/>

    <TextView android:paddingTop="5dip"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:layout_gravity="center"
              android:text="loading"
              android:textSize="14sp"
              android:textColor="?android:attr/textColorPrimary"/>
</LinearLayout>

网络内容的互联网许可

 <uses-permission android:name="android.permission.INTERNET" />

您也可以使用此片段类在您的应用中加载网页内容

https://github.com/hiteshsahu/Android-Universal-Web-Content-Loader