我有一个专为在移动设备上显示而设计的网站。所以我决定使用 Android Studio。
我想显示我的 html 文件,来自服务器,但在应用程序中有本地 css 和 js 文件。换句话说,我只想从主机加载 html 并使用应用程序中存在的 css 更改其样式。我正在使用网络视图。
我该怎么办?使用 iframe 还是其他什么?请帮我。请为我提供正确的代码。
我的 MainAtivity.java 文件:
package com.example.z5070.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String url = "http://www.example.com";
WebView view = (WebView) this.findViewById(R.id.webView);
view.loadUrl(url);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
我的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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/webView"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
/>
在 Android Studio 或 eclipse 中是一样的......简单的方法是在你的 html 文件中使用这一行。
<link type="text/css" rel="stylesheet" href="style.css">
记住将 HTML 文件、CSS 文件或 JS 文件放在同一路径中,以做到“简单”。但是您可以为您需要的每种类型文件创建一个特定的文件夹。
*使用资源文件夹来存放文件。
你基本上必须通过
webView.loadDataWithBaseURL()
注入你的CSS。请务必将您的 .css
文件放入您的 assets
文件夹中并进行相对引用。
您可以查看THIS答案以了解更多详情!
Html 文件和 CSS
如果您要使用任何 html 文件并想向其中添加 CSS,您可以将这两个文件添加到 Asset 文件夹中,然后通过
相互连接CSS:
href="file:///android_asset/myStyle.css"
HTML:
wvInfo.loadUrl("file:///android_asset/htmlFile.html")