我正在尝试学习 Android 上的 WebView 。我有几个问题。
我有一个 PHP 页面,其中有 2-3 个小段落和一个图像 是随机生成的。我怎样才能确保整个 HTML 页面 完美适合移动设备的屏幕(这样滚动条 没看到)?如果在某些情况下不可能,我怎么能 缩小图像以使其完美适合所有设备? .
第二个问题是假设我在该 HTML 页面上有一个链接。我想 当我点击这个链接(属于不同的域)时 在默认浏览器中打开,而不是 android 应用程序。 (怎么能 完成此操作)。
包 com.example.try2;
import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.Window; import android.view.WindowManager; import android.webkit.WebSettings; import android.webkit.WebView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { //Full screen requestWindowFeature(Window.FEATURE_NO_TITLE); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); WebView myWebView = (WebView) findViewById(R.id.webview); myWebView.setVerticalScrollBarEnabled(false); myWebView.setHorizontalScrollBarEnabled(false); myWebView.getSettings().setLoadWithOverviewMode(true); myWebView.getSettings().setUseWideViewPort(true); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.loadUrl("http://www.example.com/mobile/index.php"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } }
最佳答案
回答您的问题:
您实际上可能必须在 HTML/JS 代码中执行此操作。 Hook 调整大小事件并根据该设备上可用的像素数设置图片大小。这是 jQuery 中的一个示例,其中 myImage 是您的图像的 ID,myText 是页面顶部包含文本的 div 的 ID:
$(window).resize(function() { // Compute available height for image // by subtracting text div height from screen height var availableImageWidth = screen.width; var availableImageHeight = screen.height - $('myText').height(); // Get image width and height var imageWidth = $("#myImage").width(); var imageHeight = $("#myImage").height(); // Compute scale that maintains aspect ratio and fits image within screen bounds var scale = Math.min( availableImageWidth / imageWidth, availableImageHeight / imageHeight); // Set new image dimensions $("#myImage").width(imageWidth * scale); $("#myImage").height(imageHeight * scale); }
您可以通过覆盖
WebViewClient
类的shouldOverrideUrlLoading
方法来做到这一点:myWebView.setWebViewClient(new WebViewClient() { public boolean shouldOverrideUrlLoading(WebView view, String url) { // Redirect HTTP and HTTPS urls to the external browser if (url != null && URLUtil.isHttpUrl(url) || URLUtil.isHttpsUrl(url)) { view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); return true; } return false; } }
关于安卓 WebView 。在没有滚动条的情况下在屏幕上显示 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14523067/