如何在android studio中以编程方式触发图像按钮

时间:2016-11-13 11:45:36

标签: java android

我想根据存储在变量中的值触发图像按钮 例如:让变量为金额。然后,如果数量<10且数量> 50,则应触发图像按钮 在这里,通过图像按钮,我打开和关闭手电筒。所以,如果是 量> 10且<30然后手电筒开启
量> 30且<50然后手电筒关闭

其次,我从函数中获取字符串形式的值,该函数将转换为整数并存储在amount变量中。

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();
                }
            }
        });
    }

2 个答案:

答案 0 :(得分:1)

mTorchOnOffButton.callOnClick()

答案 1 :(得分:0)

您可以通过两种方式在按钮上调用click事件:

mTorchOnOffButton.performClick();

这将调用点击事件,就像您自己点击了一个按钮一样。

mTorchOnOffButton.callOnClick();

这将仅调用按钮的OnClickListener方法,与performClick()不同,它不会报告任何可访问性事件。