2016-11-13 45 views
0

我想根據存儲在變量中的值觸發圖像按鈕。
例如:讓變量爲數量。然後,如果金額大於等於50,則應該觸發圖像按鈕。
在這裏,通過imagebutton我打開和關閉手電筒。所以,如果
量> 10 < 30然後手電筒打開
量> 30 < 50然後手電筒熄滅如何在android studio中以編程方式觸發圖像按鈕

其次,我從一個函數,這是爲了讓我的字符串形式的值被轉換爲整數並存儲在變量量中。

Java代碼:

Integer amount; 
public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     Log.d("bluetooth_torch", "onCreate()"); 
     setContentView(R.layout.activity_bluetooth_torch); 

     mTorchOnOffButton = (ImageButton)findViewById(R.id.button_on_off); 
     isTorchOn = false;   
     Boolean isFlashAvailable = getApplicationContext().getPackageManager() 
       .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); 

     if (!isFlashAvailable) { 

      AlertDialog alert = new AlertDialog.Builder(bluetooth_torch_Activity.this) 
        .create(); 
      alert.setTitle("Error !!"); 
      alert.setMessage("Your device doesn't support flash light!"); 
      alert.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        // closing the application 
        finish(); 
        System.exit(0); 
       } 
      }); 
      alert.show(); 
      return; 
     } 

     mCameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE); 
     try { 
      mCameraId = mCameraManager.getCameraIdList()[0]; 
     } catch (CameraAccessException e) { 
      e.printStackTrace(); 
     } 

     amount = Integer.parseInt(DATA); 
     mTorchOnOffButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       try { 
        if (isTorchOn) { 
          turnOffFlashLight(); 
          isTorchOn = false; 
        } else { 
          turnOnFlashLight(); 
          isTorchOn = true; 
        } 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
+0

我不明白這個問題嗎?有什麼問題? – HelloSadness

+1

任何特定的原因,你不能直接調用通常會被點擊迴應的代碼? – clownba0t

+1

爲什麼不重構代碼來分離方法並在需要時調用它,而不是創建按鈕單擊的額外開銷並執行相同的任務 –

回答

1

mTorchOnOffButton.callOnClick()

0

你可以調用兩種方式點擊一個按鈕事件:

mTorchOnOffButton.performClick(); 

這將調用點擊就像你自己點擊了一個按鈕一樣。

mTorchOnOffButton.callOnClick(); 

這將只調用OnClickListener方法的按鈕,而不像performClick()它不會報告任何可訪問性事件。

相關問題