网页查看内容

发布于 2024-12-02 22:09:15 字数 162 浏览 0 评论 0原文

所以基本上我有一个显示 HTML/PHP 页面的 webview,我想要做的是让这个 webview 不显示或不加载页面的某个部分或名为“xgDock”的 HTML“div”,如下所示“div”在 web 视图中无法正确显示,并且对于我的应用程序来说是不必要的。

非常感谢您抽出时间并提前致谢。

So basically I've got a webview displaying a HTML/PHP page, what I want to do is for this webview not to display or not load a certain section of the page or an HTML 'div' that is named 'xgDock' as this 'div' doesn't display correctly in webview and is unnecessary for my app.

Thanks very much for your time and thanks in advanced.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

も星光 2024-12-09 22:09:15

这是我的 webviewfragment.java

public class WebviewFragment extends Fragment implements BackPressFragment {

//Static
public static final String HIDE_NAVIGATION = "hide_navigation";
public static final String LOAD_DATA = "loadwithdata";

//References
private Activity mAct;
private FavDbAdapter mDbHelper;

//Layout with interaction
private WebView browser;
private SwipeRefreshLayout mSwipeRefreshLayout;

//Layouts
private ImageButton webBackButton;
private ImageButton webForwButton;
private LinearLayout ll;

//HTML5 video
private View mCustomView;
private int mOriginalSystemUiVisibility;
private WebChromeClient.CustomViewCallback mCustomViewCallback;

@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Return the existing layout if there is a savedInstance of this fragment
    if (savedInstanceState != null) { return ll; }

    ll = (LinearLayout) inflater.inflate(R.layout.fragment_webview,
            container, false);

    setHasOptionsMenu(true);

    browser = (WebView) ll.findViewById(R.id.webView);
    mSwipeRefreshLayout = (SwipeRefreshLayout) ll.findViewById(R.id.refreshlayout);

    // settings some settings like zooming etc in seperate method for
    // suppresslint
    browserSettings();

    browser.setWebViewClient(new WebViewClient() {
        // Make sure any url clicked is opened in webview
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if ((url.contains("market://") || url.contains("mailto:")
                    || url.contains("play.google") || url.contains("tel:") || url
                    .contains("vid:")) == true) {
                // Load new URL Don't override URL Link
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }
            // Return true to override url loading (In this case do
            // nothing).
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(browser, url);

            adjustControls();
        }

    });

    // has all to do with progress bar
    browser.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                if (progress == 100) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            } else if (progress < 100){
                //If we do not hide the navigation, show refreshing
                if (!WebviewFragment.this.getArguments().containsKey(HIDE_NAVIGATION)  ||
                        WebviewFragment.this.getArguments().getBoolean(HIDE_NAVIGATION) == false)
                    mSwipeRefreshLayout.setRefreshing(true);
            }
        }

        @SuppressLint("InlinedApi")
        @Override
        public void onShowCustomView(View view,
                                     WebChromeClient.CustomViewCallback callback) {
            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                onHideCustomView();
                return;
            }

            // 1. Stash the current state
            mCustomView = view;
            mCustomView.setBackgroundColor(Color.BLACK);
            mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();

            // 2. Stash the custom view callback
            mCustomViewCallback = callback;

            // 3. Add the custom view to the view hierarchy
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            decor.addView(mCustomView, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));


            // 4. Change the state of the window
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE);
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @Override
        public void onHideCustomView() {
            // 1. Remove the custom view
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            decor.removeView(mCustomView);
            mCustomView = null;

            // 2. Restore the state to it's original form
            getActivity().getWindow().getDecorView()
                    .setSystemUiVisibility(mOriginalSystemUiVisibility);

            //TODO Find a better solution to the keyboard not showing after custom view is hidden
            //The user will come from landscape, so we'll first 'rotate' to portrait (rotation fixes a bug of the keybaord not showing)
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //The we'll restore to the detected orientation (by immediately rotating back, the user should not notice any difference and/or flickering).
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);

            // 3. Call the custom view callback
            mCustomViewCallback.onCustomViewHidden();
            mCustomViewCallback = null;


        }

    });

    browser.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });

    // setting an on touch listener
    browser.setOnTouchListener(new View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_UP:
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                    break;
            }
            return false;
        }
    });

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            browser.reload();
        }
    });

    return ll;
}// of oncreateview

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mAct = getActivity();

    setRetainInstance(true);

    String weburl = getArguments().getStringArray(MainActivity.FRAGMENT_DATA)[0];
    String data = getArguments().containsKey(LOAD_DATA) ? getArguments().getString(LOAD_DATA) : null;
    if (checkConnectivity() || weburl.startsWith("file:///android_asset/")) {
        //If this is the first time, load the initial url, otherwise restore the view if necessairy
        if (savedInstanceState == null) {
            //If we have HTML data to load, do so, else load the url.
            if (data != null) {
                browser.loadDataWithBaseURL(weburl, data, "text/html", "UTF-8", "");
            } else {
                browser.loadUrl(weburl);
            }
        } else if (mCustomView != null){
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            ((ViewGroup) mCustomView.getParent()).removeView(mCustomView);
            decor.addView(mCustomView, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
        }
    }

}

@Override
public void onPause() {
    super.onPause();
    browser.onPause();
}

@Override
public void onResume() {
    super.onResume();
    browser.onResume();

    if (!this.getArguments().containsKey(HIDE_NAVIGATION)  ||
            this.getArguments().getBoolean(HIDE_NAVIGATION) == false){

        ActionBar actionBar = ((AppCompatActivity) mAct)
            .getSupportActionBar();

        if (mAct instanceof WebviewActivity) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP);
        } else {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
        }

        View view = mAct.getLayoutInflater().inflate(R.layout.fragment_webview_actionbar, null);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL);
        actionBar.setCustomView(view, lp);

        webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
        webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);

        webBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoBack())
                    browser.goBack();
            }
        });
        webForwButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoForward())
                    browser.goForward();
            }
        });
    } else {
        mSwipeRefreshLayout.setEnabled(false);
    }

    adjustControls();
}

@Override
public void onStop() {
    super.onStop();

    if (!this.getArguments().containsKey(HIDE_NAVIGATION)  ||
            this.getArguments().getBoolean(HIDE_NAVIGATION) == false) {

        ActionBar actionBar = ((AppCompatActivity) getActivity())
                .getSupportActionBar();

        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.share:
        shareURL();
        return true;
    case R.id.favorite:
        mDbHelper = new FavDbAdapter(mAct);
        mDbHelper.open();

        String title = browser.getTitle();
        String url = browser.getUrl();

        if (mDbHelper.checkEvent(title, url, FavDbAdapter.KEY_WEB)) {
            // This item is new
            mDbHelper.addFavorite(title, url, FavDbAdapter.KEY_WEB);
            Toast toast = Toast.makeText(mAct,
                    getResources().getString(R.string.favorite_success),
                    Toast.LENGTH_LONG);
            toast.show();
        } else {
            Toast toast = Toast.makeText(mAct,
                    getResources().getString(R.string.favorite_duplicate),
                    Toast.LENGTH_LONG);
            toast.show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.webview_menu, menu);
}

// Checking for an internet connection
private boolean checkConnectivity() {
    boolean enabled = true;

    ConnectivityManager connectivityManager = (ConnectivityManager) mAct
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();

    if ((info == null || !info.isConnected() || !info.isAvailable())) {
        enabled = false;

        Helper.noConnection(mAct);
    }

    return enabled;
}

public void adjustControls() {
    webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
    webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);

    if (webBackButton == null || webForwButton == null) return;

    if (browser.canGoBack()) {
        webBackButton.setColorFilter(Color.argb(255, 255, 255, 255));
    } else {
        webBackButton.setColorFilter(Color.argb(255, 0, 0, 0));
    }
    if (browser.canGoForward()) {
        webForwButton.setColorFilter(Color.argb(255, 255, 255, 255));
    } else {
        webForwButton.setColorFilter(Color.argb(255, 0, 0, 0));
    }
}

// sharing
private void shareURL() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    String appname = getString(R.string.app_name);
    shareIntent.putExtra(Intent.EXTRA_TEXT,
            (getResources().getString(R.string.web_share_begin)) + appname
                    + getResources().getString(R.string.web_share_end)
                    + browser.getUrl());
    startActivity(Intent.createChooser(shareIntent, getResources()
            .getString(R.string.share)));
}

@SuppressLint("SetJavaScriptEnabled")
@SuppressWarnings("deprecation")
private void browserSettings() {
    // set javascript and zoom and some other settings
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setBuiltInZoomControls(true);
    browser.getSettings().setDisplayZoomControls(false);
    browser.getSettings().setAppCacheEnabled(true);
    browser.getSettings().setDatabaseEnabled(true);
    browser.getSettings().setDomStorageEnabled(true);
    browser.getSettings().setUseWideViewPort(true);
    browser.getSettings().setLoadWithOverviewMode(true);

    // enable all plugins (flash)
    browser.getSettings().setPluginState(PluginState.ON);
}

@Override
public boolean handleBackPress() {
    if (browser.canGoBack()){
        browser.goBack();
        return true;
    }

    return false;
}
 }

WebviewActivity.Java

public class WebviewActivity extends AppCompatActivity{

private Toolbar mToolbar;

//Options to load a webpage
public static String URL = "webview_url";
public static String OPEN_EXTERNAL = "open_external";
public static String LOAD_DATA = WebviewFragment.LOAD_DATA;
public static String HIDE_NAVIGATION = WebviewFragment.HIDE_NAVIGATION;

String mWebUrl = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Determine if we want to open this as intent or in the webview
    boolean openInWebView = true;
    if (getIntent().hasExtra(OPEN_EXTERNAL) && getIntent().getExtras().getBoolean(OPEN_EXTERNAL) == true){
        //If we have to load data directly, we can only do this locally
        if (getIntent().hasExtra(LOAD_DATA)) {
            openInWebView = false;
        }
    }

    //Determine if we would like to fragment to display navigation, based on the passed bundle arguments
    boolean hideNavigation = false;
    if (getIntent().hasExtra(HIDE_NAVIGATION) && getIntent().getExtras().getBoolean(HIDE_NAVIGATION) == true){
        hideNavigation = true;
    }

    String data = null;
    if (getIntent().hasExtra(LOAD_DATA)){
        data = getIntent().getExtras().getString(LOAD_DATA);
    }

    //opening the webview fragment with passed url
    if (getIntent().hasExtra(URL)){
        mWebUrl = getIntent().getExtras().getString(URL);
        if (openInWebView) {
            openWebFragmentForUrl(mWebUrl, hideNavigation, data);
        } else {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mWebUrl));
            startActivity(browserIntent);

            //Shutdown this activity
            finish();
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}


public void openWebFragmentForUrl(String url, boolean hideNavigation, String data){
    Fragment fragment;
    fragment = new WebviewFragment();

    // adding the data
    Bundle bundle = new Bundle();
    bundle.putStringArray(MainActivity.FRAGMENT_DATA, new String[]{url});
    bundle.putBoolean(WebviewFragment.HIDE_NAVIGATION, hideNavigation);
    if (data != null)
        bundle.putString(WebviewFragment.LOAD_DATA, data);
    fragment.setArguments(bundle);

    //Changing the fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.container, fragment)
            .commit();

    //Setting the title
    if (data == null)
        setTitle(getResources().getString(R.string.webview_title));
    else
        setTitle("");
}

@Override
public void onBackPressed() {
    Fragment webview = getSupportFragmentManager().findFragmentById(R.id.container);

    if (webview instanceof BackPressFragment) {
        boolean handled = ((WebviewFragment)webview).handleBackPress();
        if (!handled)
            super.onBackPressed();
    } else {         
        super.onBackPressed();
    }
}
}

This is my webview fragment.java

public class WebviewFragment extends Fragment implements BackPressFragment {

//Static
public static final String HIDE_NAVIGATION = "hide_navigation";
public static final String LOAD_DATA = "loadwithdata";

//References
private Activity mAct;
private FavDbAdapter mDbHelper;

//Layout with interaction
private WebView browser;
private SwipeRefreshLayout mSwipeRefreshLayout;

//Layouts
private ImageButton webBackButton;
private ImageButton webForwButton;
private LinearLayout ll;

//HTML5 video
private View mCustomView;
private int mOriginalSystemUiVisibility;
private WebChromeClient.CustomViewCallback mCustomViewCallback;

@SuppressLint("InflateParams")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //Return the existing layout if there is a savedInstance of this fragment
    if (savedInstanceState != null) { return ll; }

    ll = (LinearLayout) inflater.inflate(R.layout.fragment_webview,
            container, false);

    setHasOptionsMenu(true);

    browser = (WebView) ll.findViewById(R.id.webView);
    mSwipeRefreshLayout = (SwipeRefreshLayout) ll.findViewById(R.id.refreshlayout);

    // settings some settings like zooming etc in seperate method for
    // suppresslint
    browserSettings();

    browser.setWebViewClient(new WebViewClient() {
        // Make sure any url clicked is opened in webview
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if ((url.contains("market://") || url.contains("mailto:")
                    || url.contains("play.google") || url.contains("tel:") || url
                    .contains("vid:")) == true) {
                // Load new URL Don't override URL Link
                view.getContext().startActivity(
                        new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }
            // Return true to override url loading (In this case do
            // nothing).
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(browser, url);

            adjustControls();
        }

    });

    // has all to do with progress bar
    browser.setWebChromeClient(new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int progress) {
            if (mSwipeRefreshLayout.isRefreshing()) {
                if (progress == 100) {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            } else if (progress < 100){
                //If we do not hide the navigation, show refreshing
                if (!WebviewFragment.this.getArguments().containsKey(HIDE_NAVIGATION)  ||
                        WebviewFragment.this.getArguments().getBoolean(HIDE_NAVIGATION) == false)
                    mSwipeRefreshLayout.setRefreshing(true);
            }
        }

        @SuppressLint("InlinedApi")
        @Override
        public void onShowCustomView(View view,
                                     WebChromeClient.CustomViewCallback callback) {
            // if a view already exists then immediately terminate the new one
            if (mCustomView != null) {
                onHideCustomView();
                return;
            }

            // 1. Stash the current state
            mCustomView = view;
            mCustomView.setBackgroundColor(Color.BLACK);
            mOriginalSystemUiVisibility = getActivity().getWindow().getDecorView().getSystemUiVisibility();

            // 2. Stash the custom view callback
            mCustomViewCallback = callback;

            // 3. Add the custom view to the view hierarchy
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            decor.addView(mCustomView, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));


            // 4. Change the state of the window
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
                            View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
                            View.SYSTEM_UI_FLAG_FULLSCREEN |
                            View.SYSTEM_UI_FLAG_IMMERSIVE);
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }

        @Override
        public void onHideCustomView() {
            // 1. Remove the custom view
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            decor.removeView(mCustomView);
            mCustomView = null;

            // 2. Restore the state to it's original form
            getActivity().getWindow().getDecorView()
                    .setSystemUiVisibility(mOriginalSystemUiVisibility);

            //TODO Find a better solution to the keyboard not showing after custom view is hidden
            //The user will come from landscape, so we'll first 'rotate' to portrait (rotation fixes a bug of the keybaord not showing)
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            //The we'll restore to the detected orientation (by immediately rotating back, the user should not notice any difference and/or flickering).
            getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);

            // 3. Call the custom view callback
            mCustomViewCallback.onCustomViewHidden();
            mCustomViewCallback = null;


        }

    });

    browser.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype,
                                    long contentLength) {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setData(Uri.parse(url));
            startActivity(i);
        }
    });

    // setting an on touch listener
    browser.setOnTouchListener(new View.OnTouchListener() {
        @SuppressLint("ClickableViewAccessibility")
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                case MotionEvent.ACTION_UP:
                    if (!v.hasFocus()) {
                        v.requestFocus();
                    }
                    break;
            }
            return false;
        }
    });

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            browser.reload();
        }
    });

    return ll;
}// of oncreateview

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    mAct = getActivity();

    setRetainInstance(true);

    String weburl = getArguments().getStringArray(MainActivity.FRAGMENT_DATA)[0];
    String data = getArguments().containsKey(LOAD_DATA) ? getArguments().getString(LOAD_DATA) : null;
    if (checkConnectivity() || weburl.startsWith("file:///android_asset/")) {
        //If this is the first time, load the initial url, otherwise restore the view if necessairy
        if (savedInstanceState == null) {
            //If we have HTML data to load, do so, else load the url.
            if (data != null) {
                browser.loadDataWithBaseURL(weburl, data, "text/html", "UTF-8", "");
            } else {
                browser.loadUrl(weburl);
            }
        } else if (mCustomView != null){
            FrameLayout decor = (FrameLayout) getActivity().getWindow().getDecorView();
            ((ViewGroup) mCustomView.getParent()).removeView(mCustomView);
            decor.addView(mCustomView, new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
        }
    }

}

@Override
public void onPause() {
    super.onPause();
    browser.onPause();
}

@Override
public void onResume() {
    super.onResume();
    browser.onResume();

    if (!this.getArguments().containsKey(HIDE_NAVIGATION)  ||
            this.getArguments().getBoolean(HIDE_NAVIGATION) == false){

        ActionBar actionBar = ((AppCompatActivity) mAct)
            .getSupportActionBar();

        if (mAct instanceof WebviewActivity) {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE | ActionBar.DISPLAY_HOME_AS_UP);
        } else {
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
        }

        View view = mAct.getLayoutInflater().inflate(R.layout.fragment_webview_actionbar, null);
        LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.END | Gravity.CENTER_VERTICAL);
        actionBar.setCustomView(view, lp);

        webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
        webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);

        webBackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoBack())
                    browser.goBack();
            }
        });
        webForwButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (browser.canGoForward())
                    browser.goForward();
            }
        });
    } else {
        mSwipeRefreshLayout.setEnabled(false);
    }

    adjustControls();
}

@Override
public void onStop() {
    super.onStop();

    if (!this.getArguments().containsKey(HIDE_NAVIGATION)  ||
            this.getArguments().getBoolean(HIDE_NAVIGATION) == false) {

        ActionBar actionBar = ((AppCompatActivity) getActivity())
                .getSupportActionBar();

        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
    }

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.share:
        shareURL();
        return true;
    case R.id.favorite:
        mDbHelper = new FavDbAdapter(mAct);
        mDbHelper.open();

        String title = browser.getTitle();
        String url = browser.getUrl();

        if (mDbHelper.checkEvent(title, url, FavDbAdapter.KEY_WEB)) {
            // This item is new
            mDbHelper.addFavorite(title, url, FavDbAdapter.KEY_WEB);
            Toast toast = Toast.makeText(mAct,
                    getResources().getString(R.string.favorite_success),
                    Toast.LENGTH_LONG);
            toast.show();
        } else {
            Toast toast = Toast.makeText(mAct,
                    getResources().getString(R.string.favorite_duplicate),
                    Toast.LENGTH_LONG);
            toast.show();
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.webview_menu, menu);
}

// Checking for an internet connection
private boolean checkConnectivity() {
    boolean enabled = true;

    ConnectivityManager connectivityManager = (ConnectivityManager) mAct
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = connectivityManager.getActiveNetworkInfo();

    if ((info == null || !info.isConnected() || !info.isAvailable())) {
        enabled = false;

        Helper.noConnection(mAct);
    }

    return enabled;
}

public void adjustControls() {
    webBackButton = (ImageButton) mAct.findViewById(R.id.goBack);
    webForwButton = (ImageButton) mAct.findViewById(R.id.goForward);

    if (webBackButton == null || webForwButton == null) return;

    if (browser.canGoBack()) {
        webBackButton.setColorFilter(Color.argb(255, 255, 255, 255));
    } else {
        webBackButton.setColorFilter(Color.argb(255, 0, 0, 0));
    }
    if (browser.canGoForward()) {
        webForwButton.setColorFilter(Color.argb(255, 255, 255, 255));
    } else {
        webForwButton.setColorFilter(Color.argb(255, 0, 0, 0));
    }
}

// sharing
private void shareURL() {
    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    String appname = getString(R.string.app_name);
    shareIntent.putExtra(Intent.EXTRA_TEXT,
            (getResources().getString(R.string.web_share_begin)) + appname
                    + getResources().getString(R.string.web_share_end)
                    + browser.getUrl());
    startActivity(Intent.createChooser(shareIntent, getResources()
            .getString(R.string.share)));
}

@SuppressLint("SetJavaScriptEnabled")
@SuppressWarnings("deprecation")
private void browserSettings() {
    // set javascript and zoom and some other settings
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setBuiltInZoomControls(true);
    browser.getSettings().setDisplayZoomControls(false);
    browser.getSettings().setAppCacheEnabled(true);
    browser.getSettings().setDatabaseEnabled(true);
    browser.getSettings().setDomStorageEnabled(true);
    browser.getSettings().setUseWideViewPort(true);
    browser.getSettings().setLoadWithOverviewMode(true);

    // enable all plugins (flash)
    browser.getSettings().setPluginState(PluginState.ON);
}

@Override
public boolean handleBackPress() {
    if (browser.canGoBack()){
        browser.goBack();
        return true;
    }

    return false;
}
 }

WebviewActivity.Java

public class WebviewActivity extends AppCompatActivity{

private Toolbar mToolbar;

//Options to load a webpage
public static String URL = "webview_url";
public static String OPEN_EXTERNAL = "open_external";
public static String LOAD_DATA = WebviewFragment.LOAD_DATA;
public static String HIDE_NAVIGATION = WebviewFragment.HIDE_NAVIGATION;

String mWebUrl = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_webview);
    mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Determine if we want to open this as intent or in the webview
    boolean openInWebView = true;
    if (getIntent().hasExtra(OPEN_EXTERNAL) && getIntent().getExtras().getBoolean(OPEN_EXTERNAL) == true){
        //If we have to load data directly, we can only do this locally
        if (getIntent().hasExtra(LOAD_DATA)) {
            openInWebView = false;
        }
    }

    //Determine if we would like to fragment to display navigation, based on the passed bundle arguments
    boolean hideNavigation = false;
    if (getIntent().hasExtra(HIDE_NAVIGATION) && getIntent().getExtras().getBoolean(HIDE_NAVIGATION) == true){
        hideNavigation = true;
    }

    String data = null;
    if (getIntent().hasExtra(LOAD_DATA)){
        data = getIntent().getExtras().getString(LOAD_DATA);
    }

    //opening the webview fragment with passed url
    if (getIntent().hasExtra(URL)){
        mWebUrl = getIntent().getExtras().getString(URL);
        if (openInWebView) {
            openWebFragmentForUrl(mWebUrl, hideNavigation, data);
        } else {
            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mWebUrl));
            startActivity(browserIntent);

            //Shutdown this activity
            finish();
        }
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}


public void openWebFragmentForUrl(String url, boolean hideNavigation, String data){
    Fragment fragment;
    fragment = new WebviewFragment();

    // adding the data
    Bundle bundle = new Bundle();
    bundle.putStringArray(MainActivity.FRAGMENT_DATA, new String[]{url});
    bundle.putBoolean(WebviewFragment.HIDE_NAVIGATION, hideNavigation);
    if (data != null)
        bundle.putString(WebviewFragment.LOAD_DATA, data);
    fragment.setArguments(bundle);

    //Changing the fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.container, fragment)
            .commit();

    //Setting the title
    if (data == null)
        setTitle(getResources().getString(R.string.webview_title));
    else
        setTitle("");
}

@Override
public void onBackPressed() {
    Fragment webview = getSupportFragmentManager().findFragmentById(R.id.container);

    if (webview instanceof BackPressFragment) {
        boolean handled = ((WebviewFragment)webview).handleBackPress();
        if (!handled)
            super.onBackPressed();
    } else {         
        super.onBackPressed();
    }
}
}
小猫一只 2024-12-09 22:09:15

您有几种可能性:

  • 您可以更新网站:
    您在请求中添加一个额外的参数,即: ?noxgdock
    您在 php 页面上检查此参数。如果存在,则不要添加它。
    这样,您就不会白白加载这个 div。

  • 您无法更新网站:
    您可以在加载 DIV 后删除类似的内容:

    webView.loadUrl("javascript:(function() { " + "elem = document.getElementByName('xgDock'); if (elem) {elem.style.display = 'none; ';})()" );

或者您加载页面,删除div,然后才加载它。 (但如果你有身份验证、cookies,这可能会很痛苦)

You have several possibilities:

  • You can update the website:
    You add an extra paremeter to your request, ie: ?noxgdock
    You check this parameter on your php page.. if present, you don't add it.
    like this, you don't load this div for nothing.

  • You can't update the website:
    You can remove the DIV after it is loaded with something like that:

    webView.loadUrl("javascript:(function() { " + "elem = document.getElementByName('xgDock'); if (elem) {elem.style.display = 'none; ';})()");

Or you load the page, remove the div, and only load it after. (but it can be painful if you have authentifications, cookies, ...)

疏忽 2024-12-09 22:09:15

您可以通过 webview

http://lexandera.html 将 javascript 注入到您的 HTML 内容中。 com/2009/01/injecting-javascript-into-a-webview/

从那里你可以 document.getElementByName("xgDock").style.xxxx 并用 CSS 隐藏 它。

you can inject javascript into your HTML content via webview

http://lexandera.com/2009/01/injecting-javascript-into-a-webview/

from there you can document.getElementByName("xgDock").style.xxxx and mess with CSS to hide it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文