如何使用户按下图像按钮并按下URL链接而不打开新窗口?
private class HandleClick implements View.OnClickListener {
public void onClick(View arg0) {
if(arg0.getId()==R.id.imageButton){
((TextView) findViewById(R.id.textView2)).setText("Pressed: " + ++howManyClicks1);
Uri uri = Uri.parse("https://abr.se/happyeno/?get=happyeno_svar_put&svar_id=1");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
else if (arg0.getId()==R.id.imageButton1){
((TextView) findViewById(R.id.textView3)).setText("Pressed: " + ++howManyClicks2);
Uri uri = Uri.parse("https://abr.se/happyeno/?get=happyeno_svar_put&svar_id=2");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
else if (arg0.getId()==R.id.imageButton2){
((TextView) findViewById(R.id.textView5)).setText("Pressed: " + ++howManyClicks3);
Uri uri = Uri.parse("https://abr.se/happyeno/?get=happyeno_svar_put&svar_id=3");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
else if (arg0.getId()==R.id.imageButton4){
((TextView) findViewById(R.id.textView6)).setText("Pressed: " + ++howManyClicks4);
Uri uri = Uri.parse("https://abr.se/happyeno/?get=happyeno_svar_put&svar_id=4");
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
我希望用户在不打开新窗口的情况下按下图像按钮和URL,-clarification:我不想向用户显示当他/她按下URL链接时会发生什么的网页,只是它有被迫了。
如果您通过意图调用URL,它将打开浏览器(意味着新的选项卡),而不是这个你可以使用Web视图加载应用程序内的URL
在Xml布局中:
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
在活动中:
WebView browser = (WebView) findViewById(R.id.webview);
String url = "http://www.google.com";
browser .setWebViewClient(new MyBrowser());
browser .getSettings().setLoadsImagesAutomatically(true);
browser .getSettings().setJavaScriptEnabled(true);
browser .setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
browser .loadUrl(url);
private class MyBrowser extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
这开始了一项新活动。如果您不想开始新活动,但希望在当前活动中显示网址,则需要在当前活动的布局中添加网页视图,并在网页视图中打开网址,而不是调用startActivity。
如果您不想在外部浏览器中打开URI,则应使用WebView
您可以将WebView
添加到您的布局中
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</WebView>
然后在你的活动中:
private WebViewClient webViewClient = new WebViewClient() {
@Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toast.makeText(view.getContext(), error.getDescription(), Toast.LENGTH_SHORT).show();
}
};
通过id找到你的WebView
并设置地址打开
webView.setWebViewClient(webViewClient);
webView.loadUrl(yourUrl);