Android UI使用HTML布局方法執行個體_Android

來源:互聯網
上載者:User

很多時候我們用HTML布局會更方便直接,記錄一下。
我現在主要是直接調用伺服器的網頁(實際上是jsp的,只是返回的是html),所以需要連網,第一步添加許可權。

複製代碼 代碼如下:

<uses-permission android:name="android.permission.INTERNET" />

布局檔案直接用一個WebView,如下:

複製代碼 代碼如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

下面就可以直接寫代碼了:

複製代碼 代碼如下:

package com.yangshidesign.testgryoscope;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;
import android.widget.Toast;

public class AddEmojiActivity extends Activity {
 private WebView webView;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  this.setContentView(R.layout.activity_addemoji);
  
  webView = (WebView) this.findViewById(R.id.webView1);
  
  webView.getSettings().setJavaScriptEnabled(true);
  webView.addJavascriptInterface(new WebPlugin(), "WebPlugin");
  
  webView.loadUrl(this.getString(R.string.server_url));
 }
 
 /**
  * 外掛程式類,在html的js裡面直接調用
  */
 private class WebPlugin {
  
  @JavascriptInterface
  public void test() {
   Log.e("miquan", "kkkkkk");
   Toast.makeText(AddEmojiActivity.this, "test toast ", Toast.LENGTH_SHORT).show();
  }
  
  @JavascriptInterface
  public String test2() {
   return "something";
  }
 }
}


其中@JavascriptInterface註解是添加在每一個需要用到的方法上面的。
最後就可以直接在HTML網頁上調用了。

複製代碼 代碼如下:

<script type="text/javascript">
 function test() {
  WebPlugin.test();
  var something = WebPlugin.test2();
 }
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.