在Cordova中单击html按钮时启动新活动

时间:2014-09-18 11:07:20

标签: java javascript android cordova

我正在尝试使用Cordova和Java构建Android应用程序。 我希望构建一个意图,当在HTML代码中单击按钮时启动一个新的Intent。

这是我的HTML代码:

<!DOCTYPE html>
<html>
<head>
    <title>Demo Phonegap</title>
    <script type="text/javascript" charset="utf-8" src="cordova.js">
    </script>
</head>
<body>
<h2>Hello Android</h2>
<button onclick="openNewActivity()">test</button>
</body>
</html>

这是我的Java代码:

public class MyActivity extends DroidGap {
    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        super.loadUrl("file:///android_asset/www/index.html");
    }

    public void NewIntent()
    {
        Intent i = new Intent(this,HelpActivity.class);
        startActivity(i);
    }
}

如何在不构建插件的情况下从html文件调用NewIntent()void。

感谢您的回答 海姆。

编辑:我使用phonegap作为我的应用程序的GUI。我想在cordova html文件中点击按钮时调用另一个活动。

2 个答案:

答案 0 :(得分:4)

我不知道为什么你需要在DroidGap中启动一个活动。但是如果你想在Html的按钮点击上执行一些原生的android代码,你可以使用这种方法。

您必须使用JavascriptInterface进行WebView。

示例代码段:

//in onCreate 
appView.addJavascriptInterface(new MyJSInterface(),
            "myJSInterface");
super.loadUrl("file:///android_asset/www/index.html");


//JSInterface class
public class MyJSInterface {

    public MyJSInterface() {
        // TODO Auto-generated constructor stub
        Log.i(TAG, "constructor of jsinterface");
    }

    public void btnClick () {
        //do something
    }
}

在你的HTML中:

<button onclick="callFunction()">test</button>

在你的js中:

function callFunction(){
    myJSInterface.btnClick();
}

希望这有帮助。

答案 1 :(得分:-2)

您需要在java中创建按钮。 下面是一个例子。

Button button = (Button) findViewById(R.id.button_id);
         button.setOnClickListener(new View.OnClickListener() {
             public void onClick(View v) {
                 Intent i = new Intent(this,HelpActivity.class);
    startActivity(i);

             }
         });
     }
相关问题