在CordovaActivity中添加原生View组件
2015-11-06 15:21
225 查看
代码如下
import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.view.animation.DecelerateInterpolator; import android.widget.ImageButton; import org.apache.cordova.CordovaActivity; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebViewImpl; import org.apache.cordova.engine.SystemWebView; import org.apache.cordova.engine.SystemWebViewEngine; public class MainActivity extends CordovaActivity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); super.init(); loadUrl(launchUrl); ImageButton btnShare=(ImageButton)findViewById(R.id.btnShare); btnShare.setAlpha(0f); btnShare.animate() .alpha(1f) .setDuration(1500) .setInterpolator(new DecelerateInterpolator()) .setStartDelay(1000); btnShare.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, "分享"); intent.putExtra(Intent.EXTRA_TEXT, "欢迎访问"); startActivity(Intent.createChooser(intent, "分享到")); } }); } @Override protected CordovaWebView makeWebView() { SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView); return new CordovaWebViewImpl(new SystemWebViewEngine(webView)); } @Override protected void createViews() { //Why are we setting a constant as the ID? This should be investigated // appView.getView().setId(100); // appView.getView().setLayoutParams(new FrameLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, // ViewGroup.LayoutParams.MATCH_PARENT)); // // setContentView(appView.getView()); if (preferences.contains("BackgroundColor")) { int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK); // Background of activity: appView.getView().setBackgroundColor(backgroundColor); } appView.getView().requestFocusFromTouch(); } }
更详细的介绍看下面的文章:
Embed Cordova Webview in Android Native App
Some articles have shown how to embed cordova webview to android native application, for example:http://cordova.apache.org/docs/en/5.0.0/guide_platforms_android_webview.md.htmlhttp://richardgilmour.co.uk/2013/03/03/embedding-a-cordova-webview-in-a-native-android-app/
https://github.com/Adobe-Marketing-Cloud-Apps/app-sample-android-phonegap/wiki/Embed-Webview-in-Android-Fragment
But unfortunately, the latest release of cordova android(4.0.0) make big changes on its code base. This changes, mostly kind of design pattern, have made the methods described in above article not work. What make me confused is that the cordova official website still use the old method in its example, which may waste others a lot of time.This article will show how to cooperate with the new changes of cordova android to embed cordova webview in native android application.
Create Cordova Android Project
First of all, we need to create a cordova android project. It is better to use cordova-cli.cordova create test_cordova com.example.hello HelloWorld cordova platform add android cordova plugin add nl.x-services.plugins.toast cordova plugin add org.apache.cordova.device cordova buildThe first line of code create a new cordova project in folder test_cordova.
The second line of code add android platform for new created project.
The third and fourth line of code add two plugin for project(we will use these plugins in the example).
The last line of code build the new created project
Create Native Android Application
Google now suggest Android Studio for building android project, so we will use it here. Create a new project with blank activity using Android Studio. Here, the new created activity is calledMainActivity.
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void startCordovaActivity(View view) { Intent intent = new Intent(this, TestCordovaActivity.class); startActivity(intent); } public void startCordovaActivityWithLayout(View view) { Intent intent = new Intent(this, TestCordovaWithLayoutActivity.class); startActivity(intent); } }Nothing special, we just define two methods:
startCordovaActivityand
startCordovaActivity. These two method is bind with two buttons, which we will see later.
startCordovaActivitywill transfer to a new activity whose layout is a cordova webview created programmaticly.
startCordovaActivitywill transfer to a new activity whose layout is defined using xml layout file and embedded with a cordova webview.
Lets have a look at MainActivity's layout xml file.
<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=".MainActivity"> <Button android:text="Start Cordova Activity Without Layout" android:onClick="startCordovaActivity" android:layout_width="200dp" android:layout_height="100dp" /> <Button android:text="Start Cordova Activity With Layout" android:onClick="startCordovaActivityWithLayout" android:layout_width="200dp" android:layout_height="100dp" android:layout_marginTop="50dp"/> </LinearLayout>Two buttons are defined, corresponding to the two methods above.
TestCordovaActivity
This activity is created to show how to create an activity with a cordova webview without the need of layout xml file.public class TestCordovaActivity extends CordovaActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.init(); // Load your application launchUrl = "file:///android_asset/www/index.html"; // launchUrl = "file:///android_asset/www/index2.html"; loadUrl(launchUrl); } }Noted that we extends the
CordovaActivity, which is from cordova library and implement most of stuff in order to cooperate with a cordova webview. We don't need to set the layout xml file using
setContentViewhere, because the
CordovaActivitycreate set it for us, a default cordova webview.
TestCordovaWithLayoutActivity
This activity has its layout xml file.public class TestCordovaWithLayoutActivity extends CordovaActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_test_cordova_with_layout); super.init(); // Load your application // launchUrl = "file:///android_asset/www/index.html" launchUrl = "file:///android_asset/www/index2.html"; loadUrl(launchUrl); } @Override protected CordovaWebView makeWebView() { SystemWebView webView = (SystemWebView)findViewById(R.id.cordovaWebView); return new CordovaWebViewImpl(new SystemWebViewEngine(webView)); } @Override protected void createViews() { //Why are we setting a constant as the ID? This should be investigated // appView.getView().setId(100); // appView.getView().setLayoutParams(new FrameLayout.LayoutParams( // ViewGroup.LayoutParams.MATCH_PARENT, // ViewGroup.LayoutParams.MATCH_PARENT)); // // setContentView(appView.getView()); if (preferences.contains("BackgroundColor")) { int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK); // Background of activity: appView.getView().setBackgroundColor(backgroundColor); } appView.getView().requestFocusFromTouch(); } }Again, we need to extend the
CordovaActivity. But this time, we use
setContentViewto set layout xml explicitly. In order to make things work, we need to override two methods:
makeWebViewand
createViews.
makeWebViewis important, it use the
R.id.cordovaWebView, which we define in layout xml file(we will see later).
createViewsis not so important, we override it just because it will use
setContentViewby default. But we want to use our xml, so just comment it.
The
activity_test_cordova_with_layout.xml
<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.jimmy.embeddedcordovawebviewdemo.TestCordovaWithLayoutActivity"> <TextView android:layout_width="match_parent" android:layout_height="100dp" android:background="#FF0000" android:textColor="#FFFFFF" android:gravity="center" android:text="This is native text view" /> <org.apache.cordova.engine.SystemWebView android:id="@+id/cordovaWebView" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>We use a
org.apache.cordova.engine.SystemWebViewfrom cordova library. If you have read the articles listed above, you may remember that most of examples use
org.apache.cordova.CordovaWebView. For example, below xml file is used in cordova official site.
<org.apache.cordova.CordovaWebView android:id="@+id/tutorialView" android:layout_width="match_parent" android:layout_height="match_parent" />This still works until release 4.0.0 ... Now, the
CordovaWebViewclass has changed to an interface. So we can not use like this anymore.
Copy Cordova Android Project to Native Android Application
Now comes the most excited part, we need to copy useful stuff of cordova project to the native android project.cordova jar
The first and most important thing is that we need a cordova lib. You can download the latest cordova android 4.0.0 package, then create a jar file. Check the cordova offiicial website.Navigate to the Android package's /framework directory and run ant jar. It creates the Cordova .jar file, formed as /framework/cordova-x.x.x.jar.After creating the jar file, we need to import it into our Android Studio project. Copy the jar file tolibsfolder and add the follow line in
build.gradle.
compile files('libs/cordova-4.0.0.jar')Try to access the class in cordova lib after you finish to see if everything is ok.
www folder
Copy the www folder in cordova project to the android project. Note that the folder structure on the right is for Android Studio.platforms/android/assets/www -> src/main/assets/www
plugins
We have added plugins for cordova project above, so we need to add them to our android project.We need to use the cordova plugins in folderplatforms/android/src/, instead of
plugins/, because when you run
cordova build, cordova will copy the plugins in folder
plugins/to folder
platforms/android/src/and perform some magic under the table(the config.xml indeed).
platforms/android/src/plugin_folder -> src/main/java/
config.xml
Cordova use the config.xml for its configuration, likes plugins declarations. Note that do NOT use the file in root path of cordova project, use that in platforms folder instead.platforms/android/res/xml/config.xml -> src/main/res/xml/
Bonus
You can checkout the final project in github.相关文章推荐
- [转载]Activity中ConfigChanges属性的用法
- android之定时器AlarmManager
- Android java 与 javascript互访(相互调用)的方法例子
- Web布局连载——两栏固定布局(五)
- android上改变listView的选中颜色
- 转载:On having layout
- Android中layout属性大全
- android layout XML解析错误的解决方法
- 基于Android LayoutInflater的使用介绍
- zend Framework中的Layout(模块化得布局)详解
- Auto Layout on iOS Versions prior to 6.0 解决办法
- Android布局
- layoutSubviews 详解
- LayoutInflater与findViewById的用法
- SimpleCursorAdapter类与数据绑定
- LayoutInflater的使用
- android:layout_gravity和android:gravity属性的区别
- LayoutInflater的使用 和getSystemService系统服务
- android 选择本地图片并截剪图片保存到,sdcard指定目录中
- ExtJS之 标准布局类(针对于panel)