public class fragment02 extends Fragment {
private Button btn_color;
private Button btn_surprise;
private WebView web_view;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = View.inflate(getActivity(), R.layout.fragment02, null);
btn_color = (Button) view.findViewById(R.id.btn_color);
btn_surprise = (Button) view.findViewById(R.id.btn_surprise);
web_view = (WebView) view.findViewById(R.id.web_view);
return view;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
web_view.setWebViewClient(new WebViewClient());
web_view.setWebChromeClient(new WebChromeClient());
WebSettings settings = web_view.getSettings();
settings.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
//js调用android的方法 自己创建的类名 映射名
web_view.addJavascriptInterface(new JsToAndroid(), "android");
//加载js页面时,如果不显示 去清单文件中查找是否添加网络权限
web_view.loadUrl("https://abnerming8.github.io/abnerming.html");
btn_color.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//android调用JS的方法
web_view.loadUrl("javascript:changeColor('#d43c3c')");
}
});
btn_surprise.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
web_view.loadUrl("javascript:toast()");
}
});
}
//自定义一个类
public class JsToAndroid {
//方法名一定要跟js中的方法名一致
//** 记住:一定要加注解 **
@JavascriptInterface
public void show() {
Toast.makeText(getContext(), "杜彬", Toast.LENGTH_SHORT).show();
}
}
}