布局文件的设置
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="15dp"
android:orientation="vertical"
tools:context="cn.edu.bzu.youdao.MainActivity">
<SearchView
android:id="@+id/sv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="请输入搜索内容" />
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="false" />
</LinearLayout>
建立一个MainActivity,用来实现有道词典查询的功能
package cn.edu.bzu.youdao;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SearchView;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener {
private SearchView sv;
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sv= (SearchView) findViewById(R.id.sv);
sv.setIconifiedByDefault(false);
sv.setOnQueryTextListener(this);
sv.setSubmitButtonEnabled(true);
sv.setQueryHint("chaxun");
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new HelloWebViewClient());
}
public boolean onQueryTextSubmit(String query) {
String url = "http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=";
webView.loadUrl(url + query);
Toast.makeText(MainActivity.this, "请输入查询内容", Toast.LENGTH_SHORT).show();
return false;
}
public boolean onQueryTextChange(String newText) {
return false;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
修改AndroidManifest文件,加入上网权限
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.edu.bzu.youdao">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>
运行结果图:
遇到的问题:
MainActivity中的SearchView导入类型错误,以至于无法找到途径,将其改为import android.widget.SearchView;在运行便可以了。