我想创建一个关于摇动的webview。在当前活动的xml中,我将webview可见性视为invisibe。现在,我有这个摇晃的听众。一切都运行正常,除了我在第一次启动时开始这个震动,它在文本中显示摇动,包括我在onShake()函数中的文本。但是,我不想那样。我想忽略这次震动的第一次发射,在第二次震动之后,我想刷新震动以加载网址并将网页视图的可见性显示为可见。
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.Toast;
public class MainActivity extends Activity implements
ShakeEventManager.shakeListener {
private ShakeEventManager sd;
private static long back_pressed;
Boolean isInternetPresent = false;
private int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
createData();
sd = new ShakeEventManager();
sd.setListener(this);
sd.init(this);
}
private void createData() {
WebView web = (WebView) findViewById(R.id.webview);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setPluginsEnabled(true);
web.loadUrl("http://www.google.com");
}
@Override
public void onShake() {
count++;
if (count >= 1) {
ConnectionDetector cd = new ConnectionDetector(
getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
if (isInternetPresent) {
createData();
} else {
Toast.makeText(getApplicationContext(),
"Enable Data Connection", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onResume() {
super.onResume();
sd.register();
}
@Override
protected void onPause() {
super.onPause();
sd.deregister();
}
@Override
public void onBackPressed() {
finish();
}
}
答案 0 :(得分:0)
您的count++
变量在第一次检查条件之前首先增加值,这样您可能必须像我一样增加if
,或者您可以将此语句放在最后一个条件之后。
更改如下:
@Override
public void onShake() {
if (count++ >= 1) {
ConnectionDetector cd = new ConnectionDetector(
getApplicationContext());
isInternetPresent = cd.isConnectingToInternet();
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
if (isInternetPresent) {
createData();
} else {
Toast.makeText(getApplicationContext(),
"Enable Data Connection", Toast.LENGTH_LONG).show();
}
}
}
注意:我没有测试,但我刚看到你的代码并发现了这个 逻辑错误可能对你有所帮助:))