如何在应用程序内单击按钮打开网页?

How to open a web page on button click inside an app?

网上搜了下,Whosebug中类似的题目也试了很多,都没有解决。这就是我发布问题的原因。

我想创建一个非常简单的 android 应用程序。有一个按钮,如果用户点击那个按钮,它应该打开一个特定的网站 inside 该应用程序。就是这样。

我已经为 Android 4.1 设置了此示例项目的设置。

写代码后,我做 Build / Make Project ,然后 Build / 构建 APK ,然后将此 APK 安装到我的 android phone (Android 7.0).

安装并打开应用程序后,我按下 CONNECT 按钮,但就在此时,应用程序消失了(进入后台);它打不开网站。

这是我的代码:

MainActivity.java

package example_company.test_2;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void goToGoogle (View view) {
        goToUrl ( "http://www.google.com/");
    }

    private void goToUrl (String url) {
        Uri uriUrl = Uri.parse(url);
        Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
        startActivity(launchBrowser);
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="example_company.test_2.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <Button
        android:text="CONNECT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button"
        android:onClick="goToGoogle (MainActivity)" />
</RelativeLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example_company.test_2">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="http" android:host="www.google.com" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

那么,问题是什么? 我是不是漏掉了什么!?

EDIT1

根据@pleft 的回答更改代码后,我按下 CONNECT 按钮时出现 logcat 错误:

10-31 13:51:25.681 12178-12178/example_company.test_2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: example_company.test_2, PID: 12178
                                                                      java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                                          at android.view.View.performClick(View.java:5646)
                                                                          at android.view.View$PerformClick.run(View.java:22459)
                                                                          at android.os.Handler.handleCallback(Handler.java:761)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                          at android.os.Looper.loop(Looper.java:156)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531)
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
                                                                       Caused by: java.lang.reflect.InvocationTargetException
                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                                          at android.view.View.performClick(View.java:5646) 
                                                                          at android.view.View$PerformClick.run(View.java:22459) 
                                                                          at android.os.Handler.handleCallback(Handler.java:761) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                          at android.os.Looper.loop(Looper.java:156) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831) 
                                                                       Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {example_company.test_2/example_company.test_2.WebViewActivity}; have you declared this activity in your AndroidManifest.xml?
                                                                          at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1850)
                                                                          at android.app.Instrumentation.execStartActivity(Instrumentation.java:1544)
                                                                          at android.app.Activity.startActivityForResult(Activity.java:4391)
                                                                          at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:48)
                                                                          at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:75)
                                                                          at android.app.Activity.startActivityForResult(Activity.java:4335)
                                                                          at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:856)
                                                                          at android.app.Activity.startActivity(Activity.java:4697)
                                                                          at android.app.Activity.startActivity(Activity.java:4665)
                                                                          at example_company.test_2.MainActivity.goToUrl(MainActivity.java:25)
                                                                          at example_company.test_2.MainActivity.goToGoogle(MainActivity.java:19)
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                                                                          at android.view.View.performClick(View.java:5646) 
                                                                          at android.view.View$PerformClick.run(View.java:22459) 
                                                                          at android.os.Handler.handleCallback(Handler.java:761) 
                                                                          at android.os.Handler.dispatchMessage(Handler.java:98) 
                                                                          at android.os.Looper.loop(Looper.java:156) 
                                                                          at android.app.ActivityThread.main(ActivityThread.java:6531) 
                                                                          at java.lang.reflect.Method.invoke(Native Method) 
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941) 
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831) 

两个解决方案 -

android:onClick="goToGoogle (MainActivity)"更改为android:onClick="goToGoogle"

以编程方式在您的按钮上附加点击侦听器

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            goToGoogle(view);
        }
    });

您还可以在布局中使用 webview 并在该 webview 中加载网站

在清单中,添加 <uses-permission android:name="android.permission.INTERNET" />

& 在activity_main.xml中将android:onClick="goToGoogle (MainActivity)"改为android:onClick="goToGoogle"

谢谢

  1. 更新清单以允许互联网连接

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

  2. 创建 webview

    的布局

webview.xml

<?xml version="1.0" encoding="utf-8"?>
    <WebView  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
/>
  1. 创建 WebViewActivity class

WebViewActivity

public class WebViewActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        Intent i = getIntent();
        String url= i.getStringExtra("url");
        WebView webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        assert url != null;
        webView.loadUrl(url);
    }
}
  1. 将您的 MainActivity.goToUrl 代码更新为以下内容:

    private void goToUrl (String url) { Intent intent = new Intent(this, WebViewActivity.class); intent.putExtra("url", url); 启动活动(意图); }

  2. 更改您的 activity_main.xml 行:

    android:onClick="goToGoogle (MainActivity)"

android:onClick="goToGoogle"
  1. 要解决问题中发布的 logcat 堆栈跟踪中的错误,必须在 manifest 中声明新的 activity。所以就在这条线上方

添加以下内容:

<activity android:name=".WebViewActivity" android:theme="@android:style/Theme.NoTitleBar"/>
  1. 如果你使用 webView.getSettings().setJavaScriptEnabled(true); 会导致警告 setJavaScriptEnabled 可以将 XSS 漏洞引入你的应用程序,因此请仔细检查 !或者,如果您不想在 webview 中使用 JS,您可以简单地删除它。

更新

最终的工作代码如下所示:

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void goToGoogle (View view) {
        goToUrl ( "http://www.google.com/");
    }

    private void goToUrl (String url) {
        Intent intent = new Intent(this, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("name", "Your Title Name");
        startActivity(intent);
    }

}

WebViewActivity.java

package example_company.test_2;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.TextView;

public class WebViewActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

        Intent i = getIntent();
        String url= i.getStringExtra("url");
        WebView webView = findViewById(R.id.webview);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        assert url != null;
        webView.loadUrl(url);

        TextView textView = findViewById(R.id.name);
        textView.setText(i.getStringExtra("name"));
        textView.setOnClickListener(v -> finish());

        ImageButton imageButton = findViewById(R.id.backbtn);
        imageButton.setOnClickListener(v -> finish());
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="example_company.test_2.MainActivity">

    <Button
        android:text="CONNECT"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:id="@+id/button"
        android:onClick="goToGoogle"
        android:textAppearance="@style/TextAppearance.AppCompat.Display1" />

</RelativeLayout>

webview.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".WebViewActivity">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:theme="@style/Base.ThemeOverlay.AppCompat.Dark.ActionBar"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:popupTheme="@style/MenuStyle">

        <ImageButton
            android:id="@+id/backbtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/ic_arrow_back_black_24dp"
            android:contentDescription="Back"
            tools:ignore="HardcodedText" />

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_marginStart="10dp"
            android:layout_marginLeft="10dp"
            android:textColor="#fff"
            android:textSize="18sp"
            android:textStyle="bold" />
    </androidx.appcompat.widget.Toolbar>


    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/toolbar" />

</androidx.constraintlayout.widget.ConstraintLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example_company.test_2">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".WebViewActivity" android:theme="@android:style/Theme.NoTitleBar"/>
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

截图:

您遇到的错误是

java.lang.IllegalStateException: Could not find method goToGoogle(MainActivty)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'

onclick 需要覆盖方法,而您正在传递不同的参数。

更改您的 onClick
 android:onClick="goToGoogle (MainActivity)" 

android:onClick="goToGoogle"

使用下面的代码,它会帮你打开。它对我有用。

webView.setWebViewClient(new WebViewClient(){

 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url){
   view.loadUrl(url);
  return true;
 }
});

你也可以这样试试:

 webView = (WebView) findViewById(R.id.webView1);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl("Your URL goes here");