我有一个应用程序,其中我有WebView
我在其中显示一些网站。它有效,单击网页中的链接转到我的应用程序内的网站的下一页。但是当我点击手机的后退按钮时,它会直接进入我的应用程序。我想回到网站的上一页。我怎么能这样做?
以下是我正在使用的代码示例:
public class Webdisplay extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.webdisplay);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
Toast loadingmess = Toast.makeText(this,
"Cargando El Diario de Hoy", Toast.LENGTH_SHORT);
loadingmess.show();
WebView myWebView;
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.elsalvador.com");
myWebView.setWebViewClient(new WebViewClient());
myWebView.setInitialScale(1);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setUseWideViewPort(true);
final Activity MyActivity = this;
myWebView.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 100);
if(progress == 100)
MyActivity.setTitle(R.string.app_name);
}
});
}
}
答案 0 :(得分:458)
我在WebViews的活动中使用了类似的东西:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
编辑:
要使此代码生效,您需要向包含WebView的Activity
添加字段:
private WebView mWebView;
使用onCreate()
方法对其进行初始化,您应该很高兴。
mWebView = (WebView) findViewById(R.id.webView);
答案 1 :(得分:270)
如果使用Android 2.2及更高版本(现在是大多数设备),以下代码将为您提供所需的功能。
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
答案 2 :(得分:95)
这是我的解决方案。它也适用于片段。
webView.setOnKeyListener(new OnKeyListener()
{
@Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
答案 3 :(得分:17)
下一个按钮和进度条的完整参考:put back and next button in webview
如果您想在单击电话的后退按钮时转到后页,请使用:
@Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
你也可以像这样创建自定义后退按钮:
btnback.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (wv.canGoBack()) {
wv.goBack();
}
}
});
答案 4 :(得分:14)
为什么不使用onBackPressed()
?
@Override
public void onBackPressed()
{
// super.onBackPressed(); Do not call me!
// Go to the previous web page.
}
答案 5 :(得分:14)
还应在onBackPressed
中检查焦点 @Override
public void onBackPressed() {
if (mWebview.isFocused() && mWebview.canGoBack()) {
mWebview.goBack();
} else {
super.onBackPressed();
finish();
}
}
答案 6 :(得分:9)
这是一个确认退出的代码:
@Override
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Exit!")
.setMessage("Are you sure you want to close?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
答案 7 :(得分:6)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
答案 8 :(得分:6)
在科特林:
override fun onBackPressed() {
when {
webView.canGoBack() -> webView.goBack()
else -> super.onBackPressed()
}
}
webView-如果使用综合引用,则xml中的webview组件的ID。
答案 9 :(得分:1)
您的类上的以下库应该处理onBackKeyPressed。 canGoBack()检查webview是否可以引用上一页。如果可以,那么使用goBack()函数来引用上一页(返回)。
@Override
public void onBackPressed() {
if( mWebview.canGoBack()){
mWebview.goBack();
}else{
//Do something else. like trigger pop up. Add rate app or see more app
}
}
答案 10 :(得分:1)
FoamyGuy的第一个答案是正确的,但我还有一些补充。低信誉无法让我发表评论。如果由于某些原因您的页面无法加载,请确保设置一个标记来记录失败,然后在onBackPressed覆盖上进行检查。否则,您的 canGoBack() 将永久执行,而无需前往实际的后背活动,如果该活动存在的话:
//flag with class wide access
public boolean ploadFailFlag = false;
//your error handling override
@Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
ploadFailFlag = true; //note this change
.....
.....
}
//finally to the answer to this question:
@Override
public void onBackPressed() {
if(checkinWebView.canGoBack()){
//if page load fails, go back for web view will not go back - no page to go to - yet overriding the super
if(ploadFailFlag){
super.onBackPressed();
}else {
checkinWebView.goBack();
}
}else {
Toast.makeText(getBaseContext(), "super:", Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
答案 11 :(得分:1)
您可以尝试在Webview中尝试以下操作:
private lateinit var webView: WebView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_name, container, false)
webView = root!!.findViewById(R.id.home_web_view)
var url: String = "http://yoururl.com"
webView.settings.javaScriptEnabled = true
webView.webViewClient = WebViewClient()
webView.loadUrl(url)
webView.canGoBack()
webView.setOnKeyListener{ v, keyCode, event ->
if(keyCode == KeyEvent.KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
&& webView.canGoBack()){
webView.goBack()
return@setOnKeyListener true
}
false
}
return root
}
答案 12 :(得分:0)
这是Kotlin解决方案:
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
if (event?.action != ACTION_UP || event.keyCode != KEYCODE_BACK) {
return super.onKeyUp(keyCode, event)
}
if (mWebView.canGoBack()) {
mWebView.goBack()
} else {
finish()
}
return true
}
答案 13 :(得分:0)
科特林官方方式:
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// Check if the key event was the Back button and if there's history
if (keyCode == KeyEvent.KEYCODE_BACK && myWebView.canGoBack()) {
myWebView.goBack()
return true
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event)
}
https://developer.android.com/guide/webapps/webview.html#NavigatingHistory
答案 14 :(得分:0)
如果某人想为片段中的webView处理backPressed,那么他可以使用以下代码。
将以下代码复制到您的Activity
类(其中包含片段YourFragmmentName
)
@Override
public void onBackPressed() {
List<Fragment> fragmentList = getSupportFragmentManager().getFragments();
boolean handled = false;
for(Object f: fragmentList) {
if(f instanceof YourFragmentName) {
handled = ((YourFragmentName)f).onBackPressed();
if(handled) {
break;
}
}
}
if(!handled) {
super.onBackPressed();
}
}
将此代码复制到片段YourFragmentName
public boolean onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
return true;
} else {
return false;
}
}
注释
Activity
应该替换为您正在使用的实际Acitivity类。YourFragmentName
应该替换为片段的名称。webView
中声明YourFragmentName
,以便可以从函数内部对其进行访问。答案 15 :(得分:-1)
使用此代码返回页面,当最后一页进入页面时退出活动
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent=new Intent(LiveImage.this,DashBoard.class);
startActivity(intent);
}
答案 16 :(得分:-4)
Webview in Activity,下面代码为我工作,完成活动后加载url在webview.in onbackpressed它转到上一个活动
webView = (WebView) findViewById(R.id.info_webView);
webView.loadUrl(value);
finish();