如何使用网页开发自己的app,在网页中的按钮与自己的java代码绑定来实现打电话即javascript代码调用java代码,和java代码来调用javascript代码

1首先是如何在自己的app里用网页显示,这样可以较快的更新界面而不需要让客户端升级,方法如下:

xml文件:

<WebView 
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/web_v"
       
        />

  2在activity里绑定网页:

public class MainActivity extends ActionBarActivity {

	private WebView web;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        web=(WebView) findViewById(R.id.web_v);
        
        //相当于得到了浏览器
        WebSettings webset=web.getSettings();
        //可以设置web的属性
        webset.setJavaScriptEnabled(true);
        //下面是被网页里javascript调用的方法,即demo是前面是定义匿名内的类名,里面实现网页里javascript
        //要调用的方法
        web.addJavascriptInterface(new Object(){//在web控件里为javascript代码提供使用接口
      	  @JavascriptInterface   //注意这个别掉了
      	  public void callous()
          	{
      		  System.out.println("hahahahaha");
          		Intent intent=new Intent();
          		intent.setAction(Intent.ACTION_CALL);
          		intent.setData(Uri.parse("tel:"+"123123"));
          		startActivity(intent);
          	}
        }
        , "demo");
        String url=new String("http://192.168.61.173:8080/myweb/zp.html");  
        //加载网页到web控件里
		web.loadUrl(url);
        }
    }

  3、网页里面的按钮使用的超链接,方法如下:

<p><a onClick="window.demo.callous()">联系我们</a></p>

 其中demo为类名,callous就是demo类的方法,前面的window是标记,加不加没所谓。若后面有href=“”则默认打开本网页,会启动浏览器,因此这里不要href=“”这个属性。

  4、如何用java代码调用javascript的函数,来显示原来隐藏的内容:

  (1)首先给app添加一个控件:

<LinearLayout
        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:orientation="vertical"
     tools:context="com.example.appdemo.MainActivity$PlaceholderFragment"
     android:gravity="center_horizontal"
       >
    <WebView 
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/web_v"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt"
        android:text="获取密码"
         android:layout_weight="0"
         android:onClick="getpassword"
         
        />
    </LinearLayout>

  (2)然后网页body前里写入如下的代码,即是点击事件响应的内容,就是把id为content内容显示密码,<content>可以放入网页的任何位置

<script>
function fillContent(){
	document.getElementById("content").innerHTML="隐藏密码为:1234567890"
}
</script>
<body>
<p id="content"></p>

  (3)在activity的点击事件里添加如下代码即可

  

 public void getpassword(View v)
    {
    	web.loadUrl("javascript:fillContent()");
    }

  显示如下:1运行后,2为点击“获取密码后的网页:”

               

原文地址:https://www.cnblogs.com/bokeofzp/p/4758068.html