按钮不起作用

时间:2015-01-28 05:24:43

标签: java android button

嗨,大家好我正在尝试自己学习Android,但坚持这个问题。页面中有四个按钮,如果我点击一个按钮,其他按钮将无效。这是手电筒的代码,我正在尝试使它闪烁所需的时间。它正常闪烁,但如果我点击一个按钮,其他按钮将无法正常工作。任何人都可以给我这个问题的建议。这是代码:

MainActivity.java

 Camera camera;
boolean isFlashOn;
boolean hasFlash;
Parameters params;
Button flashOn, flashOff, button1, button2, button3, button4;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    checkFlashlight();
    getCamera();
    initFlashlightButton();
}

void checkFlashlight() {
    hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        AlertDialog alert = new AlertDialog.Builder(
                MainActivity.this).create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
        return;
    }
}

private void blink(int time) {

    do {
        turnOnFlash();
        try {
            sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        turnOffFlash();
        try {
            sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        blink(time);
    } while (time <= 10);

}


private void initFlashlightButton() {
    flashOn = (Button) findViewById(R.id.buttonOn);
    flashOff = (Button) findViewById(R.id.buttonOff);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);

    flashOn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            turnOnFlash();

        }
    });

    flashOff.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOffFlash();
        }
    });

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOnFlash();
            blink(1000);
        }
    });

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOnFlash();
            blink(500);
        }
    });

    button3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            turnOnFlash();
            blink(300);
        }
    });

    button4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isFlashOn) {
                turnOffFlash();
            } else {
                turnOnFlash();
            }
            blink(100);
        }
    });
}

private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
        }
    }
}

private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) return;
        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;
        return;
    }
}

// flash OFF
private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) return;

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        camera.stopPreview();
        isFlashOn = false;
        return;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onPause() {
    super.onPause();
    turnOffFlash();
}

@Override
protected void onRestart() {
    super.onRestart();
}

@Override
protected void onResume() {
    super.onResume();
    if (hasFlash)
        turnOnFlash();
}

@Override
protected void onStart() {
    super.onStart();
    getCamera();
}

@Override
protected void onStop() {
    super.onStop();
    if (camera != null) {
        camera.release();
        camera = null;
    }
}

activity_main.xml中:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="On"
    android:id="@+id/buttonOn"
    android:layout_marginLeft="62dp"
    android:layout_marginStart="62dp"
    android:layout_marginTop="100dp"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Off"
    android:id="@+id/buttonOff"
    android:layout_marginLeft="30dp"
    android:layout_marginStart="30dp"
    android:layout_alignTop="@+id/buttonOn"
    android:layout_toRightOf="@+id/buttonOn"
    android:layout_toEndOf="@+id/buttonOn" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="2 Seconds"
    android:id="@+id/button1"
    android:layout_marginTop="164dp"
    android:layout_below="@+id/buttonOn"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="4 seconds"
    android:id="@+id/button2"
    android:layout_alignTop="@+id/button1"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="8 seconds"
    android:id="@+id/button3"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginBottom="60dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="16 Seconds"
    android:id="@+id/button4"
    android:layout_alignBottom="@+id/button3"
    android:layout_alignLeft="@+id/buttonOff"
    android:layout_alignStart="@+id/buttonOff"
    android:layout_alignRight="@+id/button2"
    android:layout_alignEnd="@+id/button2" />

4 个答案:

答案 0 :(得分:4)

不是将new OnClickListener()分别添加到每个按钮,而是将implements OnClickListener添加到Activity类并添加相应的空格:

    @Override
    Public void onClick(View v){
        int id = v.getId();
        switch(id){
        case R.id.yourbutton1:
            //do your job here
            break;
        case R.id.yourbutton2:
            //do your second job here
            break;
        }
    }

因此,不是添加新的OnClickListener,而是为每个按钮执行此操作:

    button.setOnClickListener(this);

答案 1 :(得分:0)

你的blink方法指定do - while循环,表示它应该在时间小于或等于10时继续闪烁。但我相信这不是你想要实现的。我相信你希望闪光灯一直闪烁,直到你按下“stopFlash”按钮。

为此,您必须在活动中创建一个布尔值,让您知道可能应该停止闪存并在while循环中使用它。

步骤1在Activity

中创建一个全局布尔值
    protected boolean should_continue_flash;

步骤2在do-while循环中使用

private void blink(int time) {

do {
    turnOnFlash();
    try {
        sleep(time);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    turnOffFlash();
    try {
        sleep(time);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    blink(time);
} while (should_continue_flash);
}

步骤3添加代码使布尔返回false,以便停止闪烁

根据您的onClick(View v)方法

    case R.id.stop_blink_button:
        should_continue_flash = false;

步骤4将此项添加到启动闪烁的按钮:

    should_continue_flash = true;
    blink(your_time_here);

希望这有帮助

答案 2 :(得分:0)

现在我的代码看起来像这样。请检查一下。@ Oluwatumbi

Camera camera;
boolean isFlashOn;
boolean hasFlash;
Parameters params;
Button flashOn, flashOff, button1, button2, button3, button4;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    flashOn = (Button) findViewById(R.id.buttonOn);
    flashOff = (Button) findViewById(R.id.buttonOff);
    button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button3 = (Button) findViewById(R.id.button3);
    button4 = (Button) findViewById(R.id.button4);

    checkFlashlight();
    getCamera();
    initFlashlightButton();

}


void checkFlashlight() {
    hasFlash = getApplicationContext().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        AlertDialog alert = new AlertDialog.Builder(
                MainActivity.this).create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
        return;
    }
}
  private void blink(int time) {

  do {
      turnOnFlash();
      try {
          sleep(time);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      turnOffFlash();
      try {
          sleep(time);
      } catch (InterruptedException e) {
          e.printStackTrace();
      }
      blink(time);
  } while (isFlashOn);
}

     private void initFlashlightButton() {


    flashOn.setOnClickListener(this);
    flashOff.setOnClickListener(this);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
    button3.setOnClickListener(this);
    button4.setOnClickListener(this);
}

private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
        }
    }
}


private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) return;

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;
        return;
    }
}

// flash OFF
private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) return;

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        camera.stopPreview();
        isFlashOn = false;
        return;
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onPause() {
    super.onPause();


    turnOffFlash();
}

@Override
protected void onRestart() {
    super.onRestart();
}

@Override
protected void onResume() {
    super.onResume();


    if (hasFlash)
        turnOnFlash();
}

@Override
protected void onStart() {
    super.onStart();


    getCamera();
}

@Override
protected void onStop() {
    super.onStop();


    if (camera != null) {
        camera.release();
        camera = null;
    }
}

@Override
public void onClick(View v) {
    int id=v.getId();
    switch (id){
        case R.id.buttonOn:
            turnOnFlash();
            break;
        case R.id.buttonOff:
            isFlashOn=false;
            turnOffFlash();
            break;
        case R.id.button1:
            isFlashOn=true;
            blink(1000);
            break;
        case R.id.button2:
            isFlashOn=true;
            blink(500);
            break;
        case R.id.button3:
            isFlashOn=true;
            blink(300);
            break;
        case R.id.button4:
            isFlashOn=true;
            blink(100);
            break;

    }
}
}

答案 3 :(得分:0)

在您的活动中创建一个Timer对象,以便您可以使用和重复使用

Timer timer;

blink()方法初始化计时器并模拟闪烁,如下所示:

    timer = new Timer();
    timer.schedule(new TimerTask(){

        @Override
        public void run() {
            // TODO Auto-generated method stub
            YourActivity.this.runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    //Do the blinking job here
                }

            });
        }

    }, 0, your_time_interval_here);

停止眨眼:

    timer.cancel();
    timer.purge();

这应该对你有用

此处的文档:

  

Open Declaration void java.util.Timer.schedule(TimerTask task,long   延迟,长期)

     

public void schedule(TimerTask任务,长延迟,长时间段)已添加   在API级别1中为重复的固定延迟执行安排任务   经过一段特定的延迟。

     

<强>参数       任务要安排的任务       延迟首次执行前的时间量(以毫秒为单位)       期间后续执行之间的时间量(以毫秒为单位)。

     

引发 IllegalArgumentException如果延迟&lt; 0或周期&lt; = 0。   IllegalStateException如果已取消Timer或任务   已安排或取消。

希望这有帮助