android java js_Android JAVA和JS的通信 | 学步园

//目录结构

0_13263505111KM9.gif

//效果

0_1326350554keNE.gif

//一起来看下代码

//index.html HTML页面

function showInfo(str)

{

document.getElementById("info").innerHTML=str;

}

重Android传来的值是:

call Android from javascript

//main.xml主布局

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

android:id="@+id/sendtojs"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

android:text="发送数据到JS"

/>

android:id="@+id/fromjsdata"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

/>

android:id="@+id/sendText"

android:layout_height="wrap_content"

android:layout_width="fill_parent"

/>

android:id="@+id/web"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

/>

//JSJAVAActivity.java JAVA控制代码

package sn.len.jsjava;

import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.view.View;

import android.view.View.OnClickListener;

import android.webkit.WebView;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

public class JSJAVAActivity extends Activity implements OnClickListener

{

private WebView web_webView;

private Button but_sendToJs;

private EditText edi_sendText;

private TextView tex_fromjsdata;

private Handler handler = new Handler();

@Override

public void onCreate(Bundle savedInstanceState)

{

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

web_webView=(WebView)findViewById(R.id.web);

edi_sendText=(EditText)findViewById(R.id.sendText);

but_sendToJs=(Button)findViewById(R.id.sendtojs);

tex_fromjsdata=(TextView)findViewById(R.id.fromjsdata);

but_sendToJs.setOnClickListener(this);

//开启访问JS代码功能

web_webView.getSettings().setJavaScriptEnabled(true);

//根据地址加载网页

//文件头: file://

//文件路径: /android_asset/index.html

web_webView.loadUrl("file:///android_asset/index.html");

//参数1,把new SendToJs()这个对象构建到WEB浏览器中

//参数2,提供在WEB浏览器中好让javascript访问的对象

//例如: 在WEB中,javascript调用callAndroid(value)方法写法为window.android.callAndroid('value');

web_webView.addJavascriptInterface(new SendToJs(), "android");

}

@Override

public void onClick(View v)

{

//向浏览器发送数据,调用JS的showInfo函数

web_webView.loadUrl("javascript:showInfo('"+edi_sendText.getText().toString()+"')");

}

class SendToJs

{

public void callAndroid(final String arg)

{

//利用Handler更新UI

handler.post

(

new Runnable()

{

@Override

public void run()

{

//设置重JS发过来的数据

tex_fromjsdata.setText("重javascript发来的数据是:"+arg);

}

}

);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值