【问题标题】:how to trigger an imagebutton programmatically in android studio如何在android studio中以编程方式触发imagebutton
【发布时间】:2017-03-27 04:29:37
【问题描述】:

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

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

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

【问题讨论】:

  • 我不明白这个问题?有什么问题?
  • 您不能直接调用通常响应点击的代码的任何特殊原因?
  • 为什么不重构代码以分离方法并在必要时调用它,而不是增加按钮单击和执行相同任务的额外开销
  • mTorchOnOffButton.performClick()

标签: java android


【解决方案1】:

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

mTorchOnOffButton.performClick();

这将调用 click 事件,就像您自己单击按钮一样。

mTorchOnOffButton.callOnClick();

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

【讨论】:

    【解决方案2】:

    mTorchOnOffButton.callOnClick()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-08
      • 1970-01-01
      • 2014-07-17
      • 2011-08-31
      • 1970-01-01
      • 2017-07-15
      相关资源
      最近更新 更多